id
int64
0
458k
file_name
stringlengths
4
119
file_path
stringlengths
14
227
content
stringlengths
24
9.96M
size
int64
24
9.96M
language
stringclasses
1 value
extension
stringclasses
14 values
total_lines
int64
1
219k
avg_line_length
float64
2.52
4.63M
max_line_length
int64
5
9.91M
alphanum_fraction
float64
0
1
repo_name
stringlengths
7
101
repo_stars
int64
100
139k
repo_forks
int64
0
26.4k
repo_open_issues
int64
0
2.27k
repo_license
stringclasses
12 values
repo_extraction_date
stringclasses
433 values
2,289,700
esp8266.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp8266.cpython-310.pyc
o ’jÂd¢ã@sFddlmZddlmZmZGdd„deƒZGdd„deƒZee_dS)é)Ú ESPLoader)Ú FatalErrorÚNotImplementedInROMErrorc sòeZdZdZdZdZdgZdZdZdZ dZ d Z d Z d Z d Zd Zd ZdZdZddd dd dddddœ ZdddddœZdZgd¢gd¢gd¢gd¢gZdd „Zd!d"„Zd#d$„Zd%d&„Z‡fd'd(„Z‡fd)d*„Zd+d,„Zd4d.d/„Zd0d1„Zd2d3„Z ‡Z!S)5Ú ESP8266ROMz'Access class for ESP8266 ROM bootloaderÚESP8266FlAáéPð?éTð?é\ð?i`éé é$Né@i`rééé0éPé`é€é�) Ú512KBÚ256KBÚ1MBÚ2MBÚ4MBz2MB-c1z4MB-c1Ú8MBÚ16MBéé)Ú80mÚ40mÚ26mÚ20m)ið?ið?ÚDPORT)i€þ?i@ÚDRAM)i@i€@ÚIRAM)i @i.@ÚIROMcCsD| d¡d>}|| d¡d>O}|| d¡d>O}|| d¡O}|S)Nr riXð?r rr r)Úread_reg)ÚselfÚresult©r)ú7/home/ceco/Downloads/esptool/esptool/targets/esp8266.pyÚ get_efuses?s zESP8266ROM.get_efusescCst|d@dk}|d@dk}|d@dk}|d@dk}|r(|s(|s"|s"dS|s(|r(dS|s8|r8|s2|s2dS|s8|r8dSd S) Nrrl l l rrééÿÿÿÿr))r'ÚefusesÚr0_4Úr3_25Úr3_26Úr3_27r)r)r*Ú_get_flash_sizeGs    zESP8266ROM._get_flash_sizecCsX| ¡}|d@dk}|r*| |¡}|d@dk}|rdnd|r dnddœ |d ¡}|Sd S) Nl rr Ú ESP8285H08Ú ESP8285N08Ú ESP8285H16Ú ESP8285N16)rrÚESP8285Ú ESP8266EX)r+r3Úget)r'r.Úis_8285Ú flash_sizeÚmax_tempÚ chip_namer)r)r*Úget_chip_descriptionZs þ þ  þýzESP8266ROM.get_chip_descriptioncCs dg}d| ¡vr|dg7}|S)NÚWiFir8zEmbedded Flash)r?)r'Úfeaturesr)r)r*Úget_chip_featuresks  zESP8266ROM.get_chip_featurescs*|jr tt|ƒ |¡dS| dd¡dS)Nr)ÚIS_STUBÚsuperrÚflash_spi_attachÚ flash_begin)r'Úhspi_arg©Ú __class__r)r*rEqszESP8266ROM.flash_spi_attachcs|jr tt|ƒ |¡dSdS©N)rCrDrÚflash_set_parameters)r'ÚsizerHr)r*rKysÿzESP8266ROM.flash_set_parameterscCs,| |j¡}| |j¡}|d?|d@d>BS)z_ Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() func éiÿÿÿé)r&Ú ESP_OTP_MAC0Ú ESP_OTP_MAC1)r'Úid0Úid1r)r)r*Úchip_id~s  zESP8266ROM.chip_idÚBASE_MACcCs®|dkrdS| |j¡}| |j¡}| |j¡}|dkr,|d?d@|d?d@|d@f}n|d?d@dkr7d}n|d?d@dkrBd }ntd ƒ‚||d?d@|d@|d ?d@fS) zRead MAC from OTP ROMrTNrréÿrN)rMéþé4r)é¬éÐétz Unknown OUIrM)r&rOrPÚ ESP_OTP_MAC3r)r'Úmac_typeÚmac0Úmac1Úmac3Úouir)r)r*Úread_mac†s    "zESP8266ROM.read_maccCsbd}|j}||d|}||}|||}||kr|}|d|kr+|dd|S|||S)ztCalculate an erase size given a specific size in bytes. Provides a workaround for the bootloader erase bug.rrr)ÚFLASH_SECTOR_SIZE)r'ÚoffsetrLÚsectors_per_blockÚ sector_sizeÚ num_sectorsÚ start_sectorÚ head_sectorsr)r)r*Úget_erase_size—s   zESP8266ROM.get_erase_sizecCstdƒ‚)Nz0Overriding VDDSDIO setting only applies to ESP32)r)r'Ú new_voltager)r)r*Úoverride_vddsdioªsÿzESP8266ROM.override_vddsdio)rT)"Ú__name__Ú __module__Ú __qualname__Ú__doc__Ú CHIP_NAMErCÚCHIP_DETECT_MAGIC_VALUErOrPr[Ú SPI_REG_BASEÚ SPI_USR_OFFSÚ SPI_USR1_OFFSÚ SPI_USR2_OFFSÚSPI_MOSI_DLEN_OFFSÚSPI_MISO_DLEN_OFFSÚ SPI_W0_OFFSÚUART_CLKDIV_REGÚXTAL_CLK_DIVIDERÚ FLASH_SIZESÚFLASH_FREQUENCYÚBOOTLOADER_FLASH_OFFSETÚ MEMORY_MAPr+r3r?rBrErKrSrarirkÚ __classcell__r)r)rHr*r s`÷ üü   rc@s(eZdZdZdZdZdd„Zdd„ZdS) ÚESP8266StubLoaderz9Access class for ESP8266 stub loader, runs on top of ROM.i@TcCs,|j|_|j|_|j|_|j|_| ¡dSrJ)Úsecure_download_modeÚ_portÚ_trace_enabledÚcacheÚ flush_input)r'Ú rom_loaderr)r)r*Ú__init__¶s  zESP8266StubLoader.__init__cCs|SrJr))r'rcrLr)r)r*ri½sz ESP8266StubLoader.get_erase_sizeN)rlrmrnroÚFLASH_WRITE_SIZErCr‡rir)r)r)r*r€°s  r€N)ÚloaderrÚutilrrrr€Ú STUB_CLASSr)r)r)r*Ú<module>s ' 
5,153
Python
.pyt
33
154.363636
550
0.460156
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,701
esp32c2.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32c2.cpython-310.pyc
o ’jÂd‰ã@sRddlZddlZddlmZddlmZGdd„deƒZGdd „d eƒZee_dS) éNé)Ú ESP32C3ROMé)Ú ESPLoaderc @seZdZdZdZdZdZdZdZddgZ d Z e d Z e d Z e d Z d Ze d Zd Ze d Zd Ze d ZdZe dZe d ZdZdddddœZgd¢gd¢gd¢gd¢gd¢gd¢gd¢gd¢gZdd„Zd d!„Zd"d#„Zd$d%„Zd&d'„Zd(d)„Zd*d+„Z d,d-„Z!d.S)/Ú ESP32C2ROMúESP32-C2é éBé@Bé<é@<io0Qoio A|iˆ`é@é0i iié`éérrr)Ú60mÚ30mÚ20mÚ15m)riÚPADDING)r r ÚDROM)iÊ?iÎ?ÚDRAM)i€È?iÐ?ÚBYTE_ACCESSIBLE)ið?iõ?Ú DROM_MASK)i@i @Ú IROM_MASK)r r ÚIROM)iÀ7@i<@ÚIRAMcCó d}| |jd|¡d?d@S)Nrééé©Úread_regÚEFUSE_BLOCK2_ADDR©ÚselfÚnum_word©r(ú7/home/ceco/Downloads/esptool/esptool/targets/esp32c2.pyÚget_pkg_version@ózESP32C2ROM.get_pkg_versioncCs<dddœ | ¡d¡}| ¡}| ¡}|›d|›d|›d�S)Nr)rrzunknown ESP32-C2z (revision vÚ.ú))Úgetr*Úget_major_chip_versionÚget_minor_chip_version)r&Ú chip_nameÚ major_revÚ minor_revr(r(r)Úget_chip_descriptionDsþ ýzESP32C2ROM.get_chip_descriptioncCr)Nrrérr"r%r(r(r)r0Mr+z!ESP32C2ROM.get_minor_chip_versioncCr)Nrrérr"r%r(r(r)r/Qr+z!ESP32C2ROM.get_major_chip_versioncCs t |¡S©N)rÚget_crystal_freq©r&r(r(r)r8Us zESP32C2ROM.get_crystal_freqcCs‚|j o | ¡dk}|r9|dd}td|›�ƒ| |jt d|d¡¡tdƒ| |¡t  d¡|  ¡dSt   ||¡dS)Néé(zChanging baud rate to z<IIrzChanged.gš™™™™™©?) ÚIS_STUBr8ÚprintÚcommandÚESP_CHANGE_BAUDRATEÚstructÚpackÚ_set_port_baudrateÚtimeÚsleepÚ flush_inputrÚ change_baud)r&ÚbaudÚrom_with_26M_XTALÚfalse_rom_baudr(r(r)rFYs ÿ   zESP32C2ROM.change_baudcCs*|js| ¡dkrd|_d|_dSdSdS)NrTF)Úsecure_download_modeÚget_chip_revisionÚstub_is_disabledr<r9r(r(r)Ú _post_connectos þzESP32C2ROM._post_connectcCs˜| |j¡|j@}| |j¡|j@}|r|dkn|dk}|r dS|r'dgdndgd}tt|ƒƒD]}| |j|d¡||<||dkrIdSq2dS)NrrTrr!rF)r#ÚEFUSE_XTS_KEY_LENGTH_256_REGÚEFUSE_XTS_KEY_LENGTH_256ÚEFUSE_RD_DIS_REGÚ EFUSE_RD_DISÚrangeÚlenÚEFUSE_BLOCK_KEY0_REG)r&Ú key_len_256Úword0Ú rd_disableÚkey_wordÚir(r(r)Úis_flash_encryption_key_validws ÿÿ ÿz(ESP32C2ROM.is_flash_encryption_key_validN)"Ú__name__Ú __module__Ú __qualname__Ú CHIP_NAMEÚ IMAGE_CHIP_IDÚIROM_MAP_STARTÚ IROM_MAP_ENDÚDROM_MAP_STARTÚ DROM_MAP_ENDÚCHIP_DETECT_MAGIC_VALUEÚ EFUSE_BASEr$Ú MAC_EFUSE_REGÚEFUSE_SECURE_BOOT_EN_REGÚEFUSE_SECURE_BOOT_EN_MASKÚEFUSE_SPI_BOOT_CRYPT_CNT_REGÚEFUSE_SPI_BOOT_CRYPT_CNT_MASKÚ%EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REGÚ!EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPTrNrOrTrPrQÚFLASH_FREQUENCYÚ MEMORY_MAPr*r4r0r/r8rFrMrZr(r(r(r)r sZüø   rc@s$eZdZdZdZdZdZdd„ZdS)ÚESP32C2StubLoaderz­Access class for ESP32C2 stub loader, runs on top of ROM. (Basically the same as ESP32StubLoader, but different base class. Can possibly be made into a mixin.) i@rTcCs,|j|_|j|_|j|_|j|_| ¡dSr7)rJÚ_portÚ_trace_enabledÚcacherE)r&Ú rom_loaderr(r(r)Ú__init__�s  zESP32C2StubLoader.__init__N)r[r\r]Ú__doc__ÚFLASH_WRITE_SIZEÚSTATUS_BYTES_LENGTHr<rtr(r(r(r)ro’s  ro) r@rCÚesp32c3rÚloaderrrroÚ STUB_CLASSr(r(r(r)Ú<module>s   
4,313
Python
.pyt
36
118.388889
906
0.485855
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,702
esp32s3beta2.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32s3beta2.cpython-310.pyc
o ’jÂd|ã@s6ddlmZGdd„deƒZGdd„deƒZee_dS)é)Ú ESP32S3ROMc@seZdZdZdZdgZdZdS)ÚESP32S3BETA2ROMzESP32-S3(beta2)él6AVi `N)Ú__name__Ú __module__Ú __qualname__Ú CHIP_NAMEÚ IMAGE_CHIP_IDÚCHIP_DETECT_MAGIC_VALUEÚ EFUSE_BASE©r r ú</home/ceco/Downloads/esptool/esptool/targets/esp32s3beta2.pyr s rc@s$eZdZdZdZdZdZdd„ZdS)ÚESP32S3BETA2StubLoaderz­Access class for ESP32S3 stub loader, runs on top of ROM. (Basically the same as ESP32StubLoader, but different base class. Can possibly be made into a mixin.) i@éTcCs,|j|_|j|_|j|_|j|_| ¡dS)N)Úsecure_download_modeÚ_portÚ_trace_enabledÚcacheÚ flush_input)ÚselfÚ rom_loaderr r r Ú__init__s  zESP32S3BETA2StubLoader.__init__N)rrrÚ__doc__ÚFLASH_WRITE_SIZEÚSTATUS_BYTES_LENGTHÚIS_STUBrr r r r rs  rN)Úesp32s3rrrÚ STUB_CLASSr r r r Ú<module>s  
1,179
Python
.pyt
13
88.538462
205
0.517153
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,703
esp32s3.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32s3.cpython-310.pyc
o ’jÂd4ã@snddlZddlZddlmZddlmZddlmZddlm Z m Z Gdd „d eƒZ Gd d „d e ƒZ e e _ dS) éNé)ÚESP32ROMé)Ú ESPLoader)Ú HardReset)Ú FatalErrorÚNotImplementedInROMErrorc @sˆeZdZdZdZdgZdZdZdZdZ dZ dZ d Z d Z d Zd Zd ZdZdZdZdZdZdZedZedZedZedZedZd ZedZd ZedZdZ edZ!dZ"edZ#dZ$edZ%dZ&eZ'dZ(edZ)dZ*edZ+dZ,edZ-dZ.d Z/d!Z0dZ1d"Z2d!Z3dZ4d#Z5e5d$Z6d%Z7e5d&Z8d'Z9e5d(Z:e5d)Z;d*Z<d+Z=d,Z>d[email protected]/ZBgd0¢gd1¢gd2¢gd3¢gd4¢gd5¢gd6¢gd7¢gd8¢gd9¢gd:¢gd;¢g ZCd<d=„ZDd>d?„ZEd@dA„ZFdBdC„ZGdDdE„ZHdFdG„ZIdHdI„ZJdJdK„ZKdLdM„ZLdNdO„ZMdPdQ„ZNdRdS„ZOdTdU„ZPdVdW„ZQdXdY„ZRdZd[„ZSd\d]„ZTd^d_„ZUd`da„ZVdbdc„ZWdxdedf„ZXdgdh„ZYdidj„ZZdkdl„Z[dmdn„Z\dodp„Z]dqdr„Z^dsdt„Z_dudv„Z`dwS)yÚ ESP32S3ROMzESP32-S3é FéBiDé<é>i€`i `ééé é$é(éXrTéip`éDé\é0é4é8ééé iié<iréiLñÎ?i€`é´lé¸l*1:é˜é°i¡:ØPii8@`i,�`ri`)riÚPADDING)r é=ÚDROM)r$r Ú EXTRAM_DATA)éà`é`ÚRTC_DRAM)é€È?éÐ?ÚBYTE_ACCESSIBLE)r*i >@Ú MEM_INTERNAL)r*r+ÚDRAM)i@i¡@Ú IROM_MASK)i7@i>@ÚIRAM)r'r(ÚRTC_IRAM)r i€BÚIROM)iPi PÚRTC_DATAcCó d}| |jd|¡d?d@S)Nrréé©Úread_regÚEFUSE_BLOCK1_ADDR©ÚselfÚnum_word©r=ú7/home/ceco/Downloads/esptool/esptool/targets/esp32s3.pyÚget_pkg_versionxózESP32S3ROM.get_pkg_versioncCs$|d@dko| ¡dko| ¡dkS)Nr6rr)Úget_blk_version_majorÚget_blk_version_minor©r;Ú minor_rawr=r=r>Úis_eco0|s  ÿ ýzESP32S3ROM.is_eco0cCs| ¡}| |¡r dS|S©Nr)Úget_raw_minor_chip_versionrErCr=r=r>Úget_minor_chip_version†s z!ESP32S3ROM.get_minor_chip_versioncCsLd}| |jd|¡d?d@}d}| |jd|¡d?d@}|d>|S)Nérérrér6r7)r;Ú hi_num_wordÚhiÚ low_num_wordÚlowr=r=r>rGŒs  z%ESP32S3ROM.get_raw_minor_chip_versioncCs d}| |jd|¡d?d@S)Nrrr)r8ÚEFUSE_BLOCK2_ADDRr:r=r=r>rA“r@z ESP32S3ROM.get_blk_version_majorcCr4)Nrrrr6r7r:r=r=r>rB—r@z ESP32S3ROM.get_blk_version_minorcCs| ¡}| |¡r dS| ¡SrF)rGrEÚget_raw_major_chip_versionrCr=r=r>Úget_major_chip_version›s z!ESP32S3ROM.get_major_chip_versioncCr4)NrIrrrr7r:r=r=r>rQ¡r@z%ESP32S3ROM.get_raw_major_chip_versioncCs@| ¡}| ¡}| ¡}dddœ |d¡}|›d|›d|›d�S)NzESP32-S3 (QFN56)zESP32-S3-PICO-1 (LGA56))rrzunknown ESP32-S3z (revision vÚ.ú))rRrHr?Úget)r;Ú major_revÚ minor_revÚ pkg_versionÚ chip_namer=r=r>Úget_chip_description¥sþýzESP32S3ROM.get_chip_descriptioncCr4)Nrrér6r7r:r=r=r>Ú get_flash_cap±r@zESP32S3ROM.get_flash_capcCs8d}| |jd|¡d?d@}dddddd œ |d ¡S) Nrrr6ÚXMCÚGDÚFMÚTTÚBY)rrrrrIÚ©r8r9rU©r;r<Ú vendor_idr=r=r>Úget_flash_vendorµszESP32S3ROM.get_flash_vendorcCs d}| |jd|¡d?d@S)Nrrr7r:r=r=r>Ú get_psram_capºr@zESP32S3ROM.get_psram_capcCs2d}| |jd|¡d?d@}dddœ |d¡S)Nrr6rÚAP_3v3ÚAP_1v8)rrrbrcrdr=r=r>Úget_psram_vendor¾szESP32S3ROM.get_psram_vendorcCs€ddg}ddddœ | ¡d¡}|dur!||d| ¡›d�g7}dd d dœ | ¡d ¡}|dur>||d| ¡›d�g7}|S) NÚWiFiÚBLEzEmbedded Flash 8MBzEmbedded Flash 4MB)rrrzUnknown Embedded Flashz (rTzEmbedded PSRAM 8MBzEmbedded PSRAM 2MBzUnknown Embedded PSRAM)rUr\rfrgrj)r;ÚfeaturesÚflashÚpsramr=r=r>Úget_chip_featuresÃs$ý üý üzESP32S3ROM.get_chip_featurescCsdS)Nrr=©r;r=r=r>Úget_crystal_freqØszESP32S3ROM.get_crystal_freqcCsdS©Nr=rqr=r=r>Úget_flash_crypt_configÜsz!ESP32S3ROM.get_flash_crypt_configcCsr|dks|dkr tdƒ‚|j|jf|j|jf|j|jf|j|jf|j |j f|j |j fg|\}}|  |¡|?d@S)NrrIz,Valid key block numbers must be in range 0-5é)rÚEFUSE_PURPOSE_KEY0_REGÚEFUSE_PURPOSE_KEY0_SHIFTÚEFUSE_PURPOSE_KEY1_REGÚEFUSE_PURPOSE_KEY1_SHIFTÚEFUSE_PURPOSE_KEY2_REGÚEFUSE_PURPOSE_KEY2_SHIFTÚEFUSE_PURPOSE_KEY3_REGÚEFUSE_PURPOSE_KEY3_SHIFTÚEFUSE_PURPOSE_KEY4_REGÚEFUSE_PURPOSE_KEY4_SHIFTÚEFUSE_PURPOSE_KEY5_REGÚEFUSE_PURPOSE_KEY5_SHIFTr8)r;Ú key_blockÚregÚshiftr=r=r>Úget_key_block_purposeßs      úùz ESP32S3ROM.get_key_block_purposecs\‡fdd„tdƒDƒ}t‡fdd„|DƒƒrdSt‡fdd„|Dƒƒo-t‡fdd„|DƒƒS) Ncsg|]}ˆ |¡‘qSr=)r…)Ú.0Úbrqr=r>Ú <listcomp>ïsz<ESP32S3ROM.is_flash_encryption_key_valid.<locals>.<listcomp>éc3ó�|]}|ˆjkVqdSrs)ÚPURPOSE_VAL_XTS_AES128_KEY©r†Úprqr=r>Ú <genexpr>ñó€z;ESP32S3ROM.is_flash_encryption_key_valid.<locals>.<genexpr>Tc3rŠrs)ÚPURPOSE_VAL_XTS_AES256_KEY_1rŒrqr=r>rŽôr�c3rŠrs)ÚPURPOSE_VAL_XTS_AES256_KEY_2rŒrqr=r>rŽôs€  ÿ)ÚrangeÚany)r;Úpurposesr=rqr>Úis_flash_encryption_key_validís "ÿz(ESP32S3ROM.is_flash_encryption_key_validcCs| |j¡|j@Srs)r8ÚEFUSE_SECURE_BOOT_EN_REGÚEFUSE_SECURE_BOOT_EN_MASKrqr=r=r>Úget_secure_boot_enabledøs ÿÿz"ESP32S3ROM.get_secure_boot_enabledcCstdƒ‚)Nz1VDD_SDIO overrides are not supported for ESP32-S3)r)r;Ú new_voltager=r=r>Úoverride_vddsdioþsÿzESP32S3ROM.override_vddsdioÚBASE_MACcCsF|dkrdS| |j¡}| |jd¡}t d||¡dd…}t|ƒS)zRead MAC from EFUSE regionr›Nrz>IIr)r8Ú MAC_EFUSE_REGÚstructÚpackÚtuple)r;Úmac_typeÚmac0Úmac1Ú bitstringr=r=r>Úread_macs  zESP32S3ROM.read_maccCs| |j¡|j@r dSdS)Nrr)r8ÚEFUSE_RD_REPEAT_DATA3_REGÚ)EFUSE_RD_REPEAT_DATA3_REG_FLASH_TYPE_MASKrqr=r=r>Ú flash_type s ÿÿÿüzESP32S3ROM.flash_typecCó|jrdS| ¡|jkS)z[ Check the UARTDEV_BUF_NO register to see if USB-OTG console is being used F)Úsecure_download_modeÚ get_uart_noÚUARTDEV_BUF_NO_USB_OTGrqr=r=r>Ú uses_usb_otgózESP32S3ROM.uses_usb_otgcCr¨)z[ Check the UARTDEV_BUF_NO register to see if USB-JTAG/Serial is being used F)r©rªÚUARTDEV_BUF_NO_USB_JTAG_SERIALrqr=r=r>Úuses_usb_jtag_serialr­zESP32S3ROM.uses_usb_jtag_serialcCsv| ¡r9| |j|j¡| |jd¡| |jd¡| |j|j¡| |j| |j¡|j B¡| |jd¡dSdSrF) r¯Ú write_regÚRTC_CNTL_WDTWPROTECT_REGÚRTC_CNTL_WDT_WKEYÚRTC_CNTL_WDTCONFIG0_REGÚRTC_CNTL_SWD_WPROTECT_REGÚRTC_CNTL_SWD_WKEYÚRTC_CNTL_SWD_CONF_REGr8ÚRTC_CNTL_SWD_AUTO_FEED_ENrqr=r=r>Údisable_watchdogs$s ÿþózESP32S3ROM.disable_watchdogscCs&| ¡r|j|_|js| ¡dSdSrs)r¬Ú USB_RAM_BLOCKÚ ESP_RAM_BLOCKÚsync_stub_detectedr¸rqr=r=r>Ú _post_connect6s  ÿzESP32S3ROM._post_connectcCspt d¡dur tdƒdS| |j¡}| |j¡}||j@dkr4||j@dkr6td |  ¡¡ƒt dƒ‚dSdS)z[ Check the strapping register to see if we can reset out of download mode. ÚESPTOOL_TESTINGNz5ESPTOOL_TESTING is set, ignoring strapping mode checkrzÑWARNING: {} chip was placed into download mode using GPIO0. esptool.py can not exit the download mode over USB. To run the app, reset the chip manually. To suppress this note, set --after option to 'no_reset'.r) ÚosÚgetenvÚprintr8ÚGPIO_STRAP_REGÚRTC_CNTL_OPTION1_REGÚGPIO_STRAP_SPI_BOOT_MASKÚ!RTC_CNTL_FORCE_DOWNLOAD_BOOT_MASKÚformatrZÚ SystemExit)r;Ú strap_regÚ force_dl_regr=r=r>Ú_check_if_can_reset<s"   ÿ þÿüôzESP32S3ROM._check_if_can_resetcCs.| ¡}|r | ¡tdƒt|j|ƒƒdS)NzHard resetting via RTS pin...)r¬rÉrÀrÚ_port)r;r¬r=r=r>Ú hard_resetUs zESP32S3ROM.hard_resetcCst ||¡dSrs)rÚ change_baud)r;Úbaudr=r=r>rÌ]szESP32S3ROM.change_baudN)r›)aÚ__name__Ú __module__Ú __qualname__Ú CHIP_NAMEÚ IMAGE_CHIP_IDÚCHIP_DETECT_MAGIC_VALUEÚFPGA_SLOW_BOOTÚIROM_MAP_STARTÚ IROM_MAP_ENDÚDROM_MAP_STARTÚ DROM_MAP_ENDÚUART_DATE_REG_ADDRÚ SPI_REG_BASEÚ SPI_USR_OFFSÚ SPI_USR1_OFFSÚ SPI_USR2_OFFSÚSPI_MOSI_DLEN_OFFSÚSPI_MISO_DLEN_OFFSÚ SPI_W0_OFFSÚBOOTLOADER_FLASH_OFFSETÚSUPPORTS_ENCRYPTED_FLASHÚFLASH_ENCRYPTED_WRITE_ALIGNÚ EFUSE_BASEr9rPrœÚEFUSE_RD_REG_BASErvrwrxryrzr{r|r}r~rr€r�Ú%EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REGÚ!EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPTÚEFUSE_SPI_BOOT_CRYPT_CNT_REGÚEFUSE_SPI_BOOT_CRYPT_CNT_MASKr–r—r¥r¦r�r‘r‹ÚUARTDEV_BUF_NOr«r®ÚRTCCNTL_BASE_REGr¶r·r´rµr³r±r²r¹rÁrÃrÂrÄÚUART_CLKDIV_REGÚ MEMORY_MAPr?rErHrGrArBrRrQrZr\rfrgrjrprrrtr…r•r˜ršr¤r§r¬r¯r¸r¼rÉrËrÌr=r=r=r>r sÖô      r c@s$eZdZdZdZdZdZdd„ZdS)ÚESP32S3StubLoaderz­Access class for ESP32S3 stub loader, runs on top of ROM. (Basically the same as ESP32StubLoader, but different base class. Can possibly be made into a mixin.) i@rTcCsH|j|_|j|_|j|_|j|_| ¡| ¡r"|j|_|j|_dSdSrs) r©rÊÚ_trace_enabledÚcacheÚ flush_inputr¬r¹rºÚFLASH_WRITE_SIZE)r;Ú rom_loaderr=r=r>Ú__init__ls þzESP32S3StubLoader.__init__N)rÎrÏrÐÚ__doc__ròÚSTATUS_BYTES_LENGTHÚIS_STUBrôr=r=r=r>rîas  rî)r¾r�Úesp32rÚloaderrÚresetrÚutilrrr rîÚ STUB_CLASSr=r=r=r>Ú<module>s   T 
11,749
Python
.pyt
58
200.5
951
0.492601
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,704
esp32h2.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32h2.cpython-310.pyc
o ’jÂd% ã@s6ddlmZGdd„deƒZGdd„deƒZee_dS)é)Ú ESP32C6ROMc@s„eZdZdZdZdgZdZedZedZedZ dZ ed Z d Z d dd d dœZ dd„Zdd„Zdd„Zdd„Zdd„Zdd„ZdS)Ú ESP32H2ROMúESP32-H2él€>n/i `ééé ié$i¡:ØPéré)Ú48mÚ24mÚ16mÚ12mcCs d}| |jd|¡d?d@S)Néré©Úread_regÚEFUSE_BLOCK1_ADDR©ÚselfÚnum_word©rú7/home/ceco/Downloads/esptool/esptool/targets/esp32h2.pyÚget_pkg_version ózESP32H2ROM.get_pkg_versioncCs d}| |jd|¡d?d@S)NérérrrrrrÚget_minor_chip_version$rz!ESP32H2ROM.get_minor_chip_versioncCs d}| |jd|¡d?d@S)NrrérrrrrÚget_major_chip_version(rz!ESP32H2ROM.get_major_chip_versioncCs:ddi | ¡d¡}| ¡}| ¡}|›d|›d|›d�S)Nrrzunknown ESP32-H2z (revision vÚ.ú))Úgetrr r)rÚ chip_nameÚ major_revÚ minor_revrrrÚget_chip_description,sÿ şzESP32H2ROM.get_chip_descriptioncCsddgS)NÚBLEz IEEE802.15.4r©rrrrÚget_chip_features4szESP32H2ROM.get_chip_featurescCsdS)Nrrr)rrrÚget_crystal_freq7szESP32H2ROM.get_crystal_freqN)Ú__name__Ú __module__Ú __qualname__Ú CHIP_NAMEÚ IMAGE_CHIP_IDÚCHIP_DETECT_MAGIC_VALUEÚDR_REG_LP_WDT_BASEÚRTC_CNTL_WDTCONFIG0_REGÚRTC_CNTL_WDTWPROTECT_REGÚRTC_CNTL_SWD_CONF_REGÚRTC_CNTL_SWD_AUTO_FEED_ENÚRTC_CNTL_SWD_WPROTECT_REGÚRTC_CNTL_SWD_WKEYÚFLASH_FREQUENCYrrr r'r*r+rrrrr s,ü rc@s$eZdZdZdZdZdZdd„ZdS)ÚESP32H2StubLoaderz­Access class for ESP32H2 stub loader, runs on top of ROM. (Basically the same as ESP32StubLoader, but different base class. Can possibly be made into a mixin.) i@r TcCs,|j|_|j|_|j|_|j|_| ¡dS)N)Úsecure_download_modeÚ_portÚ_trace_enabledÚcacheÚ flush_input)rÚ rom_loaderrrrÚ__init__Gs  zESP32H2StubLoader.__init__N)r,r-r.Ú__doc__ÚFLASH_WRITE_SIZEÚSTATUS_BYTES_LENGTHÚIS_STUBrArrrrr:<s  r:N)Úesp32c6rrr:Ú STUB_CLASSrrrrÚ<module>s 3 
2,675
Python
.pyt
15
176.4
1,290
0.480075
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,705
esp32s2.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32s2.cpython-310.pyc
o ’jÂdc*ã@snddlZddlZddlmZddlmZddlmZddlm Z m Z Gdd „d eƒZ Gd d „d e ƒZ e e _ dS) éNé)ÚESP32ROMé)Ú ESPLoader)Ú HardReset)Ú FatalErrorÚNotImplementedInROMErrorc @seZdZdZdZdZdZdZdZdZ dgZ d Z d Z d Z d Zd ZdZdZdZdZdZdZdZedZedZedZedZd ZedZd ZedZdZedZ dZ!edZ"dZ#edZ$dZ%eZ&dZ'edZ(dZ)edZ*d Z+ed!Z,d"Z-dZ.d#Z/dZ0d$Z1dZ2d%Z3d&Z4dZ5d'Z6d(Z7gd)¢gd*¢gd+¢gd,¢gd-¢gd.¢gd/¢gd0¢gd1¢gd2¢gd3¢gd4¢g Z8d5d6„Z9d7d8„Z:d9d:„Z;d;d<„Z<d=d>„Z=d?d@„Z>dAdB„Z?dCdD„Z@dEdF„ZAdGdH„ZBdIdJ„ZCdKdL„ZDdedNdO„ZEdPdQ„ZFdRdS„ZGdTdU„ZHdVdW„ZIdXdY„ZJdZd[„ZKd\d]„ZLd^d_„ZMd`da„ZNdbdc„ZOddS)fÚ ESP32S2ROMúESP32-S2rFé@i¸@é?i??iÆi @?ééé é$é(éXiD A?i@?Téi A?é0éDé\é4é8rééé iiié<iéiıÿ?ii8@@?i(�@?r)riÚPADDING)r éø?ÚDROM)iP?rÚ EXTRAM_DATA)éàù?iú?ÚRTC_DRAM)r"é@ÚBYTE_ACCESSIBLE)r"é @Ú MEM_INTERNAL)iû?r$ÚDRAM)r$i¡@Ú IROM_MASK)i@é@ÚIRAM)r*r&ÚRTC_IRAM)r i€@ÚIROM)iPi PÚRTC_DATAcCs d}| |jd|¡d?d@S)Nrré©Úread_regÚEFUSE_BLOCK1_ADDR©ÚselfÚnum_word©r6ú7/home/ceco/Downloads/esptool/esptool/targets/esp32s2.pyÚget_pkg_versionhózESP32S2ROM.get_pkg_versioncCsLd}| |jd|¡d?d@}d}| |jd|¡d?d@}|d>|S)Nrrérér0)r4Ú hi_num_wordÚhiÚ low_num_wordÚlowr6r6r7Úget_minor_chip_versionls  z!ESP32S2ROM.get_minor_chip_versioncCs d}| |jd|¡d?d@S)Nrrér0r3r6r6r7Úget_major_chip_versionsr9z!ESP32S2ROM.get_major_chip_versioncCó d}| |jd|¡d?d@S)Nrrér/r0r3r6r6r7Úget_flash_versionwr9zESP32S2ROM.get_flash_versioncCó| ¡S©N)rE©r4r6r6r7Ú get_flash_cap{ózESP32S2ROM.get_flash_capcCrC)Nrrrr/r0r3r6r6r7Úget_psram_version~r9zESP32S2ROM.get_psram_versioncCrFrG)rKrHr6r6r7Ú get_psram_cap‚rJzESP32S2ROM.get_psram_capcCs d}| |jd|¡d?d@S)Nrr;)r1ÚEFUSE_BLOCK2_ADDRr3r6r6r7Úget_block2_version…szESP32S2ROM.get_block2_versioncCsNddddddœ | ¡| ¡dd¡}| ¡}| ¡}|›d |›d |›d �S) Nr z ESP32-S2FH2z ESP32-S2FH4z ESP32-S2FNR2z ESP32-S2R2)rrréfédrPzunknown ESP32-S2z (revision vÚ.ú))ÚgetrIrLrBr@)r4Ú chip_nameÚ major_revÚ minor_revr6r6r7Úget_chip_descriptionŠsûşú zESP32S2ROM.get_chip_descriptioncCs€dg}|jr |dg7}ddddœ | ¡d¡}||g7}dd d dœ | ¡d ¡}||g7}d d ddœ | ¡d¡}||g7}|S)NÚWiFizSecure Download Mode EnabledzNo Embedded FlashzEmbedded Flash 2MBzEmbedded Flash 4MB)rrrzUnknown Embedded FlashzNo Embedded PSRAMzEmbedded PSRAM 2MBzEmbedded PSRAM 4MBzUnknown Embedded PSRAMzNo calibration in BLK2 of efusez:ADC and temperature sensor calibration in BLK2 of efuse V1z:ADC and temperature sensor calibration in BLK2 of efuse V2zUnknown Calibration in BLK2)Úsecure_download_moderSrIrLrN)r4ÚfeaturesÚ flash_versionÚ psram_versionÚblock2_versionr6r6r7Úget_chip_features™s2 ı ü ı ü ı ü zESP32S2ROM.get_chip_featurescCsdS)Nrr6rHr6r6r7Úget_crystal_freq¶szESP32S2ROM.get_crystal_freqcCstdƒ‚)Nz1VDD_SDIO overrides are not supported for ESP32-S2)r)r4Ú new_voltager6r6r7Úoverride_vddsdioºsÿzESP32S2ROM.override_vddsdioÚBASE_MACcCsF|dkrdS| |j¡}| |jd¡}t d||¡dd…}t|ƒS)zRead MAC from EFUSE regionrbNrz>IIr)r1Ú MAC_EFUSE_REGÚstructÚpackÚtuple)r4Úmac_typeÚmac0Úmac1Ú bitstringr6r6r7Úread_mac¿s  zESP32S2ROM.read_maccCs| |j¡|j@r dSdS)Nrr)r1ÚEFUSE_RD_REPEAT_DATA3_REGÚ)EFUSE_RD_REPEAT_DATA3_REG_FLASH_TYPE_MASKrHr6r6r7Ú flash_typeÈs ÿÿÿüzESP32S2ROM.flash_typecCsdSrGr6rHr6r6r7Úget_flash_crypt_configĞsz!ESP32S2ROM.get_flash_crypt_configcCs| |j¡|j@SrG)r1ÚEFUSE_SECURE_BOOT_EN_REGÚEFUSE_SECURE_BOOT_EN_MASKrHr6r6r7Úget_secure_boot_enabledÓs ÿÿz"ESP32S2ROM.get_secure_boot_enabledcCsr|dks|dkr tdƒ‚|j|jf|j|jf|j|jf|j|jf|j |j f|j |j fg|\}}|  |¡|?d@S)Nréz,Valid key block numbers must be in range 0-5r/)rÚEFUSE_PURPOSE_KEY0_REGÚEFUSE_PURPOSE_KEY0_SHIFTÚEFUSE_PURPOSE_KEY1_REGÚEFUSE_PURPOSE_KEY1_SHIFTÚEFUSE_PURPOSE_KEY2_REGÚEFUSE_PURPOSE_KEY2_SHIFTÚEFUSE_PURPOSE_KEY3_REGÚEFUSE_PURPOSE_KEY3_SHIFTÚEFUSE_PURPOSE_KEY4_REGÚEFUSE_PURPOSE_KEY4_SHIFTÚEFUSE_PURPOSE_KEY5_REGÚEFUSE_PURPOSE_KEY5_SHIFTr1)r4Ú key_blockÚregÚshiftr6r6r7Úget_key_block_purposeÙs      úùz ESP32S2ROM.get_key_block_purposecs\‡fdd„tdƒDƒ}t‡fdd„|DƒƒrdSt‡fdd„|Dƒƒo-t‡fdd„|DƒƒS) Ncsg|]}ˆ |¡‘qSr6)rƒ)Ú.0ÚbrHr6r7Ú <listcomp>ész<ESP32S2ROM.is_flash_encryption_key_valid.<locals>.<listcomp>éc3ó�|]}|ˆjkVqdSrG)ÚPURPOSE_VAL_XTS_AES128_KEY©r„ÚprHr6r7Ú <genexpr>ëó€z;ESP32S2ROM.is_flash_encryption_key_valid.<locals>.<genexpr>Tc3rˆrG)ÚPURPOSE_VAL_XTS_AES256_KEY_1rŠrHr6r7rŒîr�c3rˆrG)ÚPURPOSE_VAL_XTS_AES256_KEY_2rŠrHr6r7rŒîs€  ÿ)ÚrangeÚany)r4Úpurposesr6rHr7Úis_flash_encryption_key_validçs "ÿz(ESP32S2ROM.is_flash_encryption_key_validcCs|jrdS| ¡|jkS)z[ Check the UARTDEV_BUF_NO register to see if USB-OTG console is being used F)rYÚ get_uart_noÚUARTDEV_BUF_NO_USB_OTGrHr6r6r7Ú uses_usb_otgòszESP32S2ROM.uses_usb_otgcCs| ¡r |j|_dSdSrG)r–Ú USB_RAM_BLOCKÚ ESP_RAM_BLOCKrHr6r6r7Ú _post_connectús ÿzESP32S2ROM._post_connectcCspt d¡dur tdƒdS| |j¡}| |j¡}||j@dkr4||j@dkr6td |  ¡¡ƒt dƒ‚dSdS)z[ Check the strapping register to see if we can reset out of download mode. ÚESPTOOL_TESTINGNz5ESPTOOL_TESTING is set, ignoring strapping mode checkrzÑWARNING: {} chip was placed into download mode using GPIO0. esptool.py can not exit the download mode over USB. To run the app, reset the chip manually. To suppress this note, set --after option to 'no_reset'.r) ÚosÚgetenvÚprintr1ÚGPIO_STRAP_REGÚRTC_CNTL_OPTION1_REGÚGPIO_STRAP_SPI_BOOT_MASKÚ!RTC_CNTL_FORCE_DOWNLOAD_BOOT_MASKÚformatrWÚ SystemExit)r4Ú strap_regÚ force_dl_regr6r6r7Ú_check_if_can_resetşs"   ÿ şÿüôzESP32S2ROM._check_if_can_resetcCs.| ¡}|r | ¡tdƒt|j|ƒƒdS)NzHard resetting via RTS pin...)r–r¦r�rÚ_port)r4r–r6r6r7Ú hard_resets zESP32S2ROM.hard_resetcCst ||¡dSrG)rÚ change_baud)r4Úbaudr6r6r7r©szESP32S2ROM.change_baudN)rb)PÚ__name__Ú __module__Ú __qualname__Ú CHIP_NAMEÚ IMAGE_CHIP_IDÚFPGA_SLOW_BOOTÚIROM_MAP_STARTÚ IROM_MAP_ENDÚDROM_MAP_STARTÚ DROM_MAP_ENDÚCHIP_DETECT_MAGIC_VALUEÚ SPI_REG_BASEÚ SPI_USR_OFFSÚ SPI_USR1_OFFSÚ SPI_USR2_OFFSÚSPI_MOSI_DLEN_OFFSÚSPI_MISO_DLEN_OFFSÚ SPI_W0_OFFSrcÚUART_CLKDIV_REGÚSUPPORTS_ENCRYPTED_FLASHÚFLASH_ENCRYPTED_WRITE_ALIGNÚ EFUSE_BASEÚEFUSE_RD_REG_BASEr2rMrtrurvrwrxryrzr{r|r}r~rÚ%EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REGÚ!EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPTÚEFUSE_SPI_BOOT_CRYPT_CNT_REGÚEFUSE_SPI_BOOT_CRYPT_CNT_MASKrprqrlrmr�r�r‰ÚUARTDEV_BUF_NOr•r—r�r rŸr¡Ú MEMORY_MAPr8r@rBrErIrKrLrNrWr^r_rarkrnrorrrƒr“r–r™r¦r¨r©r6r6r6r7r s´ô    r c@s$eZdZdZdZdZdZdd„ZdS)ÚESP32S2StubLoaderz®Access class for ESP32-S2 stub loader, runs on top of ROM. (Basically the same as ESP32StubLoader, but different base class. Can possibly be made into a mixin.) i@rTcCsH|j|_|j|_|j|_|j|_| ¡| ¡r"|j|_|j|_dSdSrG) rYr§Ú_trace_enabledÚcacheÚ flush_inputr–r—r˜ÚFLASH_WRITE_SIZE)r4Ú rom_loaderr6r6r7Ú__init__.s şzESP32S2StubLoader.__init__N)r«r¬r­Ú__doc__rÌÚSTATUS_BYTES_LENGTHÚIS_STUBrÎr6r6r6r7rÈ#s  rÈ)r›rdÚesp32rÚloaderrÚresetrÚutilrrr rÈÚ STUB_CLASSr6r6r6r7Ú<module>s    
10,102
Python
.pyt
55
181.836364
1,041
0.517667
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,706
__init__.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/__init__.cpython-310.pyc
o ’jÂdbã @sÊddlmZddlmZddlmZddlmZddlm Z ddl m Z ddl m Z ddlmZdd lmZdd lmZdd lmZdd lmZeeeeeee e eeee d œ Zee ¡ƒZee ¡ƒZdS)é)ÚESP32ROM)Ú ESP32C2ROM)Ú ESP32C3ROM)Ú ESP32C6ROM)ÚESP32C6BETAROM)Ú ESP32H2ROM)ÚESP32H2BETA1ROM)ÚESP32H2BETA2ROM)Ú ESP32S2ROM)Ú ESP32S3ROM)ÚESP32S3BETA2ROM)Ú ESP8266ROM) Úesp8266Úesp32Úesp32s2Ú esp32s3beta2Úesp32s3Úesp32c3Ú esp32c6betaÚ esp32h2beta1Ú esp32h2beta2Úesp32c2Úesp32c6Úesp32h2N)rrrrrrrrrrrrrrrr rr rr rr rr Ú CHIP_DEFSÚlistÚkeysÚ CHIP_LISTÚvaluesÚROM_LIST©r r ú8/home/ceco/Downloads/esptool/esptool/targets/__init__.pyÚ<module>s6           ô 
885
Python
.pyt
12
72.666667
228
0.551487
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,707
esp32c3.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32c3.cpython-310.pyc
o ’jÂd–"ã@sZddlZddlmZddlmZddlmZmZGdd„deƒZGd d „d eƒZ e e_ dS) éNé)ÚESP32ROMé)Ú ESPLoader)Ú FatalErrorÚNotImplementedInROMErrorc @søeZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdZddgZdZdZdZedZedZedZedZd ZedZd ZedZdZedZdZ edZ!dZ"edZ#dZ$eZ%dZ&edZ'dZ(edZ)dZ*dZ+dZ,dZ-d Z.d!Z/d"Z0e0d#Z1d$Z2e0d%Z3d&Z4e0d'Z5e0d(Z6d)Z7gd*¢gd+¢gd,¢gd-¢gd.¢gd/¢gd0¢gd1¢gd2¢gd3¢gd4¢g Z8d5d6„Z9d7d8„Z:d9d:„Z;d;d<„Z<d=d>„Z=d?d@„Z>dAdB„Z?dCdD„Z@dEdF„ZAd[dHdI„ZBdJdK„ZCdLdM„ZDdNdO„ZEdPdQ„ZFdRdS„ZGdTdU„ZHdVdW„ZIdXdY„ZJdZS)\Ú ESP32C3ROMzESP32-C3éFéBé€Bé<é€<i `ééé é$é(éXrioP!iioP1i|`i`iˆ`éDé0é4é8ééé iiTéi|ğÍ?éi€`é¬lé°l*1:é�é¨i¡:ØP)riÚPADDING)r r ÚDROM)iÈ?iÎ?ÚDRAM)i€È?iĞ?ÚBYTE_ACCESSIBLE)iğ?iò?Ú DROM_MASK)i@i@Ú IROM_MASK)r r ÚIROM)iÀ7@i>@ÚIRAM)éPé PÚRTC_IRAM)r)r*ÚRTC_DRAM)ià`i`Ú MEM_INTERNAL2cCó d}| |jd|¡d?d@S)Nrréé©Úread_regÚEFUSE_BLOCK1_ADDR©ÚselfÚnum_word©r7ú7/home/ceco/Downloads/esptool/esptool/targets/esp32c3.pyÚget_pkg_versionfózESP32C3ROM.get_pkg_versioncCsLd}| |jd|¡d?d@}d}| |jd|¡d?d@}|d>|S)Nr rérrér0r1)r5Ú hi_num_wordÚhiÚ low_num_wordÚlowr7r7r8Úget_minor_chip_versionjs  z!ESP32C3ROM.get_minor_chip_versioncCr.)Nr rrrr1r4r7r7r8Úget_major_chip_versionqr:z!ESP32C3ROM.get_major_chip_versioncCr.)Nrrér0r1r4r7r7r8Ú get_flash_capur:zESP32C3ROM.get_flash_capcCs8d}| |jd|¡d?d@}dddddd œ |d ¡S) Nrrr0ÚXMCÚGDÚFMÚTTÚZBIT)rrrrr Ú)r2r3Úget)r5r6Ú vendor_idr7r7r8Úget_flash_vendoryszESP32C3ROM.get_flash_vendorcCs@dddddœ | ¡d¡}| ¡}| ¡}|›d|›d|›d �S) NzESP32-C3 (QFN32)zESP8685 (QFN28)zESP32-C3 AZ (QFN32)zESP8686 (QFN24))rrrrzunknown ESP32-C3z (revision vÚ.ú))rKr9rBrA)r5Ú chip_nameÚ major_revÚ minor_revr7r7r8Úget_chip_description~sü ûzESP32C3ROM.get_chip_descriptioncCsJddg}ddddddœ | ¡d¡}|dur#||d | ¡›d �g7}|S) NÚWiFiÚBLEzEmbedded Flash 4MBzEmbedded Flash 2MBzEmbedded Flash 1MBzEmbedded Flash 8MB)rrrrrzUnknown Embedded Flashz (rO)rKrDrM)r5ÚfeaturesÚflashr7r7r8Úget_chip_features‰sû úzESP32C3ROM.get_chip_featurescCsdS)Nrr7©r5r7r7r8Úget_crystal_freq—szESP32C3ROM.get_crystal_freqcCstdƒ‚)Nz1VDD_SDIO overrides are not supported for ESP32-C3)r)r5Ú new_voltager7r7r8Úoverride_vddsdio›sÿzESP32C3ROM.override_vddsdioÚBASE_MACcCsF|dkrdS| |j¡}| |jd¡}t d||¡dd…}t|ƒS)zRead MAC from EFUSE regionr]Nrz>IIr)r2Ú MAC_EFUSE_REGÚstructÚpackÚtuple)r5Úmac_typeÚmac0Úmac1Ú bitstringr7r7r8Úread_mac s  zESP32C3ROM.read_maccCsdS©Nr7rYr7r7r8Úget_flash_crypt_config©sz!ESP32C3ROM.get_flash_crypt_configcCs| |j¡|j@Srg)r2ÚEFUSE_SECURE_BOOT_EN_REGÚEFUSE_SECURE_BOOT_EN_MASKrYr7r7r8Úget_secure_boot_enabled¬s ÿÿz"ESP32C3ROM.get_secure_boot_enabledcCsr|dks|dkr tdƒ‚|j|jf|j|jf|j|jf|j|jf|j |j f|j |j fg|\}}|  |¡|?d@S)Nrr z,Valid key block numbers must be in range 0-5é)rÚEFUSE_PURPOSE_KEY0_REGÚEFUSE_PURPOSE_KEY0_SHIFTÚEFUSE_PURPOSE_KEY1_REGÚEFUSE_PURPOSE_KEY1_SHIFTÚEFUSE_PURPOSE_KEY2_REGÚEFUSE_PURPOSE_KEY2_SHIFTÚEFUSE_PURPOSE_KEY3_REGÚEFUSE_PURPOSE_KEY3_SHIFTÚEFUSE_PURPOSE_KEY4_REGÚEFUSE_PURPOSE_KEY4_SHIFTÚEFUSE_PURPOSE_KEY5_REGÚEFUSE_PURPOSE_KEY5_SHIFTr2)r5Ú key_blockÚregÚshiftr7r7r8Úget_key_block_purpose²s      úùz ESP32C3ROM.get_key_block_purposecs,‡fdd„tdƒDƒ}t‡fdd„|DƒƒS)Ncsg|]}ˆ |¡‘qSr7)r|)Ú.0ÚbrYr7r8Ú <listcomp>Âsz<ESP32C3ROM.is_flash_encryption_key_valid.<locals>.<listcomp>éc3s�|]}|ˆjkVqdSrg)ÚPURPOSE_VAL_XTS_AES128_KEY)r}ÚprYr7r8Ú <genexpr>Äs€z;ESP32C3ROM.is_flash_encryption_key_valid.<locals>.<genexpr>)ÚrangeÚany)r5Úpurposesr7rYr8Úis_flash_encryption_key_validÀsz(ESP32C3ROM.is_flash_encryption_key_validcCst ||¡dSrg)rÚ change_baud)r5Úbaudr7r7r8rˆÆszESP32C3ROM.change_baudcCs|jrdS| ¡|jkS)z[ Check the UARTDEV_BUF_NO register to see if USB-JTAG/Serial is being used F)Úsecure_download_modeÚ get_uart_noÚUARTDEV_BUF_NO_USB_JTAG_SERIALrYr7r7r8Úuses_usb_jtag_serialÉszESP32C3ROM.uses_usb_jtag_serialcCsv| ¡r9| |j|j¡| |jd¡| |jd¡| |j|j¡| |j| |j¡|j B¡| |jd¡dSdS)Nr) r�Ú write_regÚRTC_CNTL_WDTWPROTECT_REGÚRTC_CNTL_WDT_WKEYÚRTC_CNTL_WDTCONFIG0_REGÚRTC_CNTL_SWD_WPROTECT_REGÚRTC_CNTL_SWD_WKEYÚRTC_CNTL_SWD_CONF_REGr2ÚRTC_CNTL_SWD_AUTO_FEED_ENrYr7r7r8Údisable_watchdogsÑs ÿşózESP32C3ROM.disable_watchdogscCs|js | ¡dSdSrg)Úsync_stub_detectedr–rYr7r7r8Ú _post_connectãs ÿzESP32C3ROM._post_connectN)r])KÚ__name__Ú __module__Ú __qualname__Ú CHIP_NAMEÚ IMAGE_CHIP_IDÚFPGA_SLOW_BOOTÚIROM_MAP_STARTÚ IROM_MAP_ENDÚDROM_MAP_STARTÚ DROM_MAP_ENDÚ SPI_REG_BASEÚ SPI_USR_OFFSÚ SPI_USR1_OFFSÚ SPI_USR2_OFFSÚSPI_MOSI_DLEN_OFFSÚSPI_MISO_DLEN_OFFSÚ SPI_W0_OFFSÚBOOTLOADER_FLASH_OFFSETÚCHIP_DETECT_MAGIC_VALUEÚUART_DATE_REG_ADDRÚUART_CLKDIV_REGÚ EFUSE_BASEr3r^ÚEFUSE_RD_REG_BASErmrnrorprqrrrsrtrurvrwrxÚ%EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REGÚ!EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPTÚEFUSE_SPI_BOOT_CRYPT_CNT_REGÚEFUSE_SPI_BOOT_CRYPT_CNT_MASKrirjr�ÚSUPPORTS_ENCRYPTED_FLASHÚFLASH_ENCRYPTED_WRITE_ALIGNÚUARTDEV_BUF_NOrŒÚRTCCNTL_BASE_REGr”r•r’r“r‘r�r�Ú MEMORY_MAPr9rArBrDrMrSrXrZr\rfrhrkr|r‡rˆr�r–r˜r7r7r7r8r s¨õ    rc@s$eZdZdZdZdZdZdd„ZdS)ÚESP32C3StubLoaderz­Access class for ESP32C3 stub loader, runs on top of ROM. (Basically the same as ESP32StubLoader, but different base class. Can possibly be made into a mixin.) i@rTcCs,|j|_|j|_|j|_|j|_| ¡dSrg)rŠÚ_portÚ_trace_enabledÚcacheÚ flush_input)r5Ú rom_loaderr7r7r8Ú__init__ós  zESP32C3StubLoader.__init__N)r™ršr›Ú__doc__ÚFLASH_WRITE_SIZEÚSTATUS_BYTES_LENGTHÚIS_STUBr¿r7r7r7r8r¹ès  r¹) r_Úesp32rÚloaderrÚutilrrrr¹Ú STUB_CLASSr7r7r7r8Ú<module>s  \ 
8,156
Python
.pyt
39
207.358974
1,239
0.514353
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,708
esp32c6beta.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32c6beta.cpython-310.pyc
o ’jÂdã@s ddlmZGdd„deƒZdS)é)Ú ESP32C3ROMc@s.eZdZdZdZdgZdZdd„Zdd„Zd S) ÚESP32C6BETAROMzESP32-C6(beta)éio€¡ icCs<dddœ | ¡d¡}| ¡}| ¡}|›d|›d|›d�S)NzESP32-C6 (QFN40)zESP32-C6FH4 (QFN32))érzunknown ESP32-C6z (revision vÚ.ú))ÚgetÚget_pkg_versionÚget_major_chip_versionÚget_minor_chip_version)ÚselfÚ chip_nameÚ major_revÚ minor_rev©rú;/home/ceco/Downloads/esptool/esptool/targets/esp32c6beta.pyÚget_chip_descriptionsþ ýz#ESP32C6BETAROM.get_chip_descriptioncCsdS)Nr)r rrrÚ _post_connectszESP32C6BETAROM._post_connectN) Ú__name__Ú __module__Ú __qualname__Ú CHIP_NAMEÚ IMAGE_CHIP_IDÚCHIP_DETECT_MAGIC_VALUEÚUART_DATE_REG_ADDRrrrrrrr s rN)Úesp32c3rrrrrrÚ<module>s 
1,029
Python
.pyt
5
204.6
628
0.50439
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,709
esp32h2beta1.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32h2beta1.cpython-310.pyc
o ’jÂdlã@sNddlZddlmZddlmZmZGdd„deƒZGdd „d eƒZee_dS) éNé)Ú ESP32C3ROMé)Ú FatalErrorÚNotImplementedInROMErrorc@sReZdZdZdZdZdZdZdZdZ dZ d Z d Z d Z d Zd ZdZdgZdZdZedZedZedZedZdZedZd ZedZdZedZdZedZdZ edZ!dZ"eZ#dZ$edZ%dZ&edZ'dZ(dZ)dZ*dZ+gZ,ddddd œZ-d!d"„Z.d#d$„Z/d%d&„Z0d'd(„Z1d)d*„Z2d+d,„Z3d-d.„Z4d;d0d1„Z5d2d3„Z6d4d5„Z7d6d7„Z8d8d9„Z9d:S)<ÚESP32H2BETA1ROMzESP32-H2(beta1)é iBi€Bi<i€<i `ééé é$é(éXrl"LMi|`i `éDé0é4é8ééé iiTéérr)Ú48mÚ24mÚ16mÚ12mcCs d}| |jd|¡d?d@S)Nrré©Úread_regÚEFUSE_BLOCK1_ADDR©ÚselfÚnum_word©r#ú</home/ceco/Downloads/esptool/esptool/targets/esp32h2beta1.pyÚget_pkg_versionNózESP32H2BETA1ROM.get_pkg_versioncCs d}| |jd|¡d?d@S)Nérérrr r#r#r$Úget_minor_chip_versionRr&z&ESP32H2BETA1ROM.get_minor_chip_versioncCs d}| |jd|¡d?d@S)Nr'rérr r#r#r$Úget_major_chip_versionVr&z&ESP32H2BETA1ROM.get_major_chip_versioncCs:ddi | ¡d¡}| ¡}| ¡}|›d|›d|›d�S)NrzESP32-H2zunknown ESP32-H2z (revision vÚ.ú))Úgetr%r+r))r!Ú chip_nameÚ major_revÚ minor_revr#r#r$Úget_chip_descriptionZsÿ şz$ESP32H2BETA1ROM.get_chip_descriptioncCsddgS)NÚBLEz IEEE802.15.4r#©r!r#r#r$Úget_chip_featuresbsz!ESP32H2BETA1ROM.get_chip_featurescCsdS)Nr r#r4r#r#r$Úget_crystal_freqeóz ESP32H2BETA1ROM.get_crystal_freqcCstdƒ‚)Nz1VDD_SDIO overrides are not supported for ESP32-H2)r)r!Ú new_voltager#r#r$Úoverride_vddsdiohsÿz ESP32H2BETA1ROM.override_vddsdioÚBASE_MACcCsF|dkrdS| |j¡}| |jd¡}t d||¡dd…}t|ƒS)zRead MAC from EFUSE regionr:Nrz>IIr)rÚ MAC_EFUSE_REGÚstructÚpackÚtuple)r!Úmac_typeÚmac0Úmac1Ú bitstringr#r#r$Úread_macms  zESP32H2BETA1ROM.read_maccCódS©Nr#r4r#r#r$Úget_flash_crypt_configvr7z&ESP32H2BETA1ROM.get_flash_crypt_configcCsr|dks|dkr tdƒ‚|j|jf|j|jf|j|jf|j|jf|j |j f|j |j fg|\}}|  |¡|?d@S)Nréz,Valid key block numbers must be in range 0-5r)rÚEFUSE_PURPOSE_KEY0_REGÚEFUSE_PURPOSE_KEY0_SHIFTÚEFUSE_PURPOSE_KEY1_REGÚEFUSE_PURPOSE_KEY1_SHIFTÚEFUSE_PURPOSE_KEY2_REGÚEFUSE_PURPOSE_KEY2_SHIFTÚEFUSE_PURPOSE_KEY3_REGÚEFUSE_PURPOSE_KEY3_SHIFTÚEFUSE_PURPOSE_KEY4_REGÚEFUSE_PURPOSE_KEY4_SHIFTÚEFUSE_PURPOSE_KEY5_REGÚEFUSE_PURPOSE_KEY5_SHIFTr)r!Ú key_blockÚregÚshiftr#r#r$Úget_key_block_purposeys      úùz%ESP32H2BETA1ROM.get_key_block_purposecs,‡fdd„tdƒDƒ}t‡fdd„|DƒƒS)Ncsg|]}ˆ |¡‘qSr#)rW)Ú.0Úbr4r#r$Ú <listcomp>‰szAESP32H2BETA1ROM.is_flash_encryption_key_valid.<locals>.<listcomp>éc3s�|]}|ˆjkVqdSrE)ÚPURPOSE_VAL_XTS_AES128_KEY)rXÚpr4r#r$Ú <genexpr>‹s€[email protected]_flash_encryption_key_valid.<locals>.<genexpr>)ÚrangeÚany)r!Úpurposesr#r4r$Úis_flash_encryption_key_valid‡sz-ESP32H2BETA1ROM.is_flash_encryption_key_validcCrDrEr#r4r#r#r$Ú _post_connect�r7zESP32H2BETA1ROM._post_connectN)r:):Ú__name__Ú __module__Ú __qualname__Ú CHIP_NAMEÚ IMAGE_CHIP_IDÚIROM_MAP_STARTÚ IROM_MAP_ENDÚDROM_MAP_STARTÚ DROM_MAP_ENDÚ SPI_REG_BASEÚ SPI_USR_OFFSÚ SPI_USR1_OFFSÚ SPI_USR2_OFFSÚSPI_MOSI_DLEN_OFFSÚSPI_MISO_DLEN_OFFSÚ SPI_W0_OFFSÚBOOTLOADER_FLASH_OFFSETÚCHIP_DETECT_MAGIC_VALUEÚUART_DATE_REG_ADDRÚ EFUSE_BASErr;ÚEFUSE_RD_REG_BASErHrIrJrKrLrMrNrOrPrQrRrSÚ%EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REGÚ!EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPTÚEFUSE_SPI_BOOT_CRYPT_CNT_REGÚEFUSE_SPI_BOOT_CRYPT_CNT_MASKÚEFUSE_SECURE_BOOT_EN_REGÚEFUSE_SECURE_BOOT_EN_MASKr\ÚSUPPORTS_ENCRYPTED_FLASHÚFLASH_ENCRYPTED_WRITE_ALIGNÚ MEMORY_MAPÚFLASH_FREQUENCYr%r)r+r2r5r6r9rCrFrWrbrcr#r#r#r$r sxü   rc@s$eZdZdZdZdZdZdd„ZdS)ÚESP32H2BETA1StubLoaderz²Access class for ESP32H2BETA1 stub loader, runs on top of ROM. (Basically the same as ESP32StubLoader, but different base class. Can possibly be made into a mixin.) i@rTcCs,|j|_|j|_|j|_|j|_| ¡dSrE)Úsecure_download_modeÚ_portÚ_trace_enabledÚcacheÚ flush_input)r!Ú rom_loaderr#r#r$Ú__init__œs  zESP32H2BETA1StubLoader.__init__N)rdrerfÚ__doc__ÚFLASH_WRITE_SIZEÚSTATUS_BYTES_LENGTHÚIS_STUBrŠr#r#r#r$rƒ‘s  rƒ) r<Úesp32c3rÚutilrrrrƒÚ STUB_CLASSr#r#r#r$Ú<module>s  
5,690
Python
.pyt
27
209.222222
2,133
0.524634
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,710
esp32h2beta2.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32h2beta2.cpython-310.pyc
o ’jÂd•ã@s6ddlmZGdd„deƒZGdd„deƒZee_dS)é)ÚESP32H2BETA1ROMc@s"eZdZdZdZdgZdd„ZdS)ÚESP32H2BETA2ROMúESP32-H2(beta2)éio°�hcCs:ddi | ¡d¡}| ¡}| ¡}|›d|›d|›d�S)Nrrzunknown ESP32-H2z (revision vÚ.ú))ÚgetÚget_pkg_versionÚget_major_chip_versionÚget_minor_chip_version)ÚselfÚ chip_nameÚ major_revÚ minor_rev©rú</home/ceco/Downloads/esptool/esptool/targets/esp32h2beta2.pyÚget_chip_descriptionsÿ şz$ESP32H2BETA2ROM.get_chip_descriptionN)Ú__name__Ú __module__Ú __qualname__Ú CHIP_NAMEÚ IMAGE_CHIP_IDÚCHIP_DETECT_MAGIC_VALUErrrrrr s  rc@s$eZdZdZdZdZdZdd„ZdS)ÚESP32H2BETA2StubLoaderz²Access class for ESP32H2BETA2 stub loader, runs on top of ROM. (Basically the same as ESP32StubLoader, but different base class. Can possibly be made into a mixin.) i@éTcCs,|j|_|j|_|j|_|j|_| ¡dS)N)Úsecure_download_modeÚ_portÚ_trace_enabledÚcacheÚ flush_input)r Ú rom_loaderrrrÚ__init__#s  zESP32H2BETA2StubLoader.__init__N)rrrÚ__doc__ÚFLASH_WRITE_SIZEÚSTATUS_BYTES_LENGTHÚIS_STUBr!rrrrrs  rN)Ú esp32h2beta1rrrÚ STUB_CLASSrrrrÚ<module>s  
1,529
Python
.pyt
11
136.727273
650
0.523715
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,711
esp32.cpython-310.pyc
OLIMEX_RVPC/SOFTWARE/rvpc/esptool/esptool/targets/__pycache__/esp32.cpython-310.pyc
o ’jÂdi5ã@sVddlZddlZddlmZddlmZmZGdd„deƒZGdd„deƒZee_ dS) éNé)Ú ESPLoader)Ú FatalErrorÚNotSupportedErrorc@sÔeZdZdZdZdZdZdZdgZdZ dZ d Z d Z d Z d Zd ZdZdZdZdZdZedZdZeZdZedZdZdZdZedZdZdZdZ dZ!dZ"dZ#dZ$dZ%ddddd d!d"d#d$œZ&d%ddd&d'œZ'd(Z(gd)¢Z)gd*¢gd+¢gd,¢gd-¢gd.¢gd/¢gd0¢gd1¢gd2¢gd3¢gd4¢gd5¢gd6¢gd7¢gd8¢gZ*dZ+ d9d:„Z,d;d<„Z-d=d>„Z.d?d@„Z/dAdB„Z0dCdD„Z1dEdF„Z2dGdH„Z3dIdJ„Z4dKdL„Z5dMdN„Z6dOdP„Z7dQdR„Z8dadTdU„Z9dVdW„Z:dXdY„Z;dZd[„Z<d\d]„Z=d^d_„Z>d`S)bÚESP32ROMz%Access class for ESP32 ROM bootloaderÚESP32rFTiƒðé @é@@é@?é€?éi ô?éé é$é(é,i õ?éé€iðéi`ö?é|ééiô?ilðõ?iÿÿÿéé0é@éPé`ép)Ú1MBÚ2MBÚ4MBÚ8MBÚ16MBÚ32MBÚ64MBÚ128MBér)Ú80mÚ40mÚ26mÚ20mé)z1.8Vú1.9VÚOFF)riÚPADDING)r r ÚDROM)r iÀ?Ú EXTRAM_DATA)iø?i ø?ÚRTC_DRAM)iù?é@ÚBYTE_ACCESSIBLE)iàú?r2ÚDRAM)iþ?iüÿÿ?Ú DIRAM_DRAM)r2é@ÚIROM)r6é€@Ú CACHE_PRO)r8é@Ú CACHE_APP)r:é @ÚIRAM)r<iüÿ @Ú DIRAM_IRAM)i @i @ÚRTC_IRAM)rr r7)iPi PÚRTC_DATAcCsb| d¡}|d?d@}|rdSdgd}tt|ƒƒD]}| d|¡||<||dkr.dSqdS)znBit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1 this bit is at position 16 in EFUSE_BLK0_RDATA0_REGrrrTréF)Ú read_efuseÚrangeÚlen)ÚselfÚword0Ú rd_disableÚkey_wordÚi©rJú5/home/ceco/Downloads/esptool/esptool/targets/esp32.pyÚis_flash_encryption_key_validns    ÿz&ESP32ROM.is_flash_encryption_key_validcCs>| d¡}|d?d@}|dkr | d¡}|d?d@}|SdS)aØFor flash encryption related commands we need to make sure user has programmed all the relevant efuse correctly so before writing encrypted write_flash_encrypt esptool will verify the values of flash_crypt_config to be non zero if they are not read protected. If the values are zero a warning will be printed bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config this bit is at position 19 in EFUSE_BLK0_RDATA0_REGrérér r&©rB)rErFrGÚword5rJrJrKÚget_flash_crypt_config…s   zESP32ROM.get_flash_crypt_configcCs| |j¡|j@S©N)Úread_regÚ%EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT_REGÚ!EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT©rErJrJrKÚget_encrypted_download_disabled›s ÿÿz(ESP32ROM.get_encrypted_download_disabledcCs(| |j¡|j@}t|ƒ d¡d@dkS)NÚ1rr)rSÚEFUSE_SPI_BOOT_CRYPT_CNT_REGÚEFUSE_SPI_BOOT_CRYPT_CNT_MASKÚbinÚcount)rEÚflash_crypt_cntrJrJrKÚget_flash_encryption_enabled¡s ÿÿz%ESP32ROM.get_flash_encryption_enabledcCs0| |j¡}| ¡}||j@p|dko||j@S)Ni,)rSÚEFUSE_RD_ABS_DONE_REGÚget_chip_revisionÚEFUSE_RD_ABS_DONE_0_MASKÚEFUSE_RD_ABS_DONE_1_MASK)rEÚefusesÚrevrJrJrKÚget_secure_boot_enabled©s  ÿz ESP32ROM.get_secure_boot_enabledcCs.| d¡}|d?d@}||d?d@d>7}|S)Néé rrrrO)rEÚword3Ú pkg_versionrJrJrKÚget_pkg_version°s  zESP32ROM.get_pkg_versioncCs| ¡d| ¡S)Néd)Úget_major_chip_versionÚget_minor_chip_versionrVrJrJrKr`¶szESP32ROM.get_chip_revisioncCs| d¡d?d@S)NrNrrfrOrVrJrJrKrm¹szESP32ROM.get_minor_chip_versioncCsn| d¡d?d@}| d¡d?d@}| |j¡}||j?|j@}|d>|d>B|B}dddddœ |d¡}|S) Nrfr&rrNérr)rrrfr)rBrSÚAPB_CTL_DATE_ADDRÚAPB_CTL_DATE_SÚAPB_CTL_DATE_VÚget)rEÚrev_bit0Úrev_bit1Ú apb_ctl_dateÚrev_bit2Ú combine_valueÚrevisionrJrJrKrl¼s üûzESP32ROM.get_major_chip_versioncCsŽ| ¡}| ¡}| ¡}|dk}| d¡d@}|rdnd|r dnddd|r'd nd d d d œ |d¡}| d¡r<|r<|d7}|›d|›d|›d�S)Nrfrz ESP32-S0WDQ6z ESP32-D0WDQ6z ESP32-S0WDz ESP32-D0WDz ESP32-D2WDz ESP32-U4WDHz ESP32-PICO-V3z ESP32-PICO-D4zESP32-PICO-V3-02zESP32-D0WDR2-V3)rrrr rNérz unknown ESP32z-V3z (revision vÚ.ú))rjrlrmrBrrÚ startswith)rEriÚ major_revÚ minor_revÚrev3Ú single_coreÚ chip_namerJrJrKÚget_chip_descriptionËs$   ùø zESP32ROM.get_chip_descriptionc Csdg}| d¡}|d@}|dkr|dg7}|d@}|r!|dg7}n|dg7}|d @}|r=|d @}|r8|d g7}n|d g7}| ¡}|d vrJ|dg7}|dkrS|dg7}| d¡}|d?d@} | re|dg7}|d?d@} | rr|dg7}| d¡} | d@} |ddddddœ| g7}|S)NÚWiFirfrrÚBTrz Single Corez Dual Corei r+Ú160MHzÚ240MHz)rr rNryzEmbedded FlashryzEmbedded PSRAMr érzVRef calibration in efuserAzBLK3 partially reservedzCoding Scheme %sÚNonez3/4zRepeat (UNSUPPORTED)ÚInvalid)rrrrf)rBrj) rEÚfeaturesrhÚchip_ver_dis_btÚchip_ver_dis_app_cpuÚchip_cpu_freq_ratedÚchip_cpu_freq_lowriÚword4Úadc_vrefÚ blk3_part_resÚword6Ú coding_schemerJrJrKÚget_chip_featuresâsJ               ÿÿÿzESP32ROM.get_chip_featurescCs| |jd|¡S)z,Read the nth word of the ESP3x EFUSE region.r )rSÚEFUSE_RD_REG_BASE)rEÚnrJrJrKrBszESP32ROM.read_efusecCs t|dƒ‚)NÚchip_id)rrVrJrJrKr—s zESP32ROM.chip_idÚBASE_MACcCsF|dkrdS| d¡| d¡g}tjdg|¢RŽ}|dd…}t|ƒS)zRead MAC from EFUSE regionr˜Nrrz>IIr‡)rBÚstructÚpackÚtuple)rEÚmac_typeÚwordsÚ bitstringrJrJrKÚread_macs  zESP32ROM.read_maccCs|SrRrJ)rEÚoffsetÚsizerJrJrKÚget_erase_size'szESP32ROM.get_erase_sizec Cs†| ¡}||jvr tdƒ‚d}d}d}d}d}d}d}|} | |O} |d kr)| |O} |d kr5| ||B|BO} | || ¡td |ƒdS) Nz@The only accepted VDDSDIO overrides are '1.8V', '1.9V' and 'OFF'it€ô?li`iii@i r-r,zVDDSDIO regulator set to %s)ÚupperÚOVERRIDE_VDDSDIO_CHOICESrÚ write_regÚprint) rEÚ new_voltageÚRTC_CNTL_SDIO_CONF_REGÚRTC_CNTL_XPD_SDIO_REGÚRTC_CNTL_DREFH_SDIO_MÚRTC_CNTL_DREFM_SDIO_MÚRTC_CNTL_DREFL_SDIO_MÚRTC_CNTL_SDIO_FORCEÚRTC_CNTL_SDIO_PD_ENÚreg_valrJrJrKÚoverride_vddsdio*s, ÿ ÿ zESP32ROM.override_vddsdioc Cs¶d}d}t|ƒ|krYt||t|ƒƒ}| d|jt d|t|ƒ|¡¡}t|ƒ|kr4td|t|ƒfƒ‚||d|…7}|rSt|ƒddksLt|ƒ|krS|t|ƒ|ƒt|ƒ|ks |S)Nrózread flash blockú<IIz4Expected %d byte block, got %d bytes. Serial errors?ir)rDÚminÚ check_commandÚESP_READ_FLASH_SLOWr™ršr)rEr ÚlengthÚ progress_fnÚ BLOCK_LENÚdataÚ block_lenÚrrJrJrKÚread_flash_slowFs( ý  ÿÿ  ðzESP32ROM.read_flash_slowcCs:| |j¡|j?|j@}| d¡d@}|d|d}|S)zA Get the crystal frequency calculated by the ROM r éÿi =r)rSÚ RTCCALICFG1ÚTIMERS_RTC_CALI_VALUE_SÚTIMERS_RTC_CALI_VALUErB)rEÚcali_valÚ clk_8M_freqÚrom_calculated_freqrJrJrKÚget_rom_cal_crystal_freq]s þz!ESP32ROM.get_rom_cal_crystal_freqcCsˆ|jdks Jdƒ‚| ¡}|dkrdnd}t|||ƒ}td|›�ƒ| |jt d|d¡¡td ƒ| |¡t   d ¡|  ¡dS) Nrz*This workaround should only apply to ESP32i@Š÷iZbi€ºŒzChanging baud rate to r²rzChanged.gš™™™™™©?) Ú CHIP_NAMErÄÚintr¦ÚcommandÚESP_CHANGE_BAUDRATEr™ršÚ_set_port_baudrateÚtimeÚsleepÚ flush_input)rEÚbaudrÃÚ valid_freqÚfalse_rom_baudrJrJrKÚ change_baudks   zESP32ROM.change_baudN)r˜)?Ú__name__Ú __module__Ú __qualname__Ú__doc__rÅÚ IMAGE_CHIP_IDÚIS_STUBÚFPGA_SLOW_BOOTÚCHIP_DETECT_MAGIC_VALUEÚIROM_MAP_STARTÚ IROM_MAP_ENDÚDROM_MAP_STARTÚ DROM_MAP_ENDÚSTATUS_BYTES_LENGTHÚ SPI_REG_BASEÚ SPI_USR_OFFSÚ SPI_USR1_OFFSÚ SPI_USR2_OFFSÚSPI_MOSI_DLEN_OFFSÚSPI_MISO_DLEN_OFFSr•rTrUrYrZr_rarbÚDR_REG_SYSCON_BASErorqrpÚ SPI_W0_OFFSÚUART_CLKDIV_REGÚXTAL_CLK_DIVIDERr¾rÀr¿Ú FLASH_SIZESÚFLASH_FREQUENCYÚBOOTLOADER_FLASH_OFFSETr¤Ú MEMORY_MAPÚFLASH_ENCRYPTED_WRITE_ALIGNrLrQrWr^rerjr`rmrlr‚r”rBr—rŸr¢r°r¼rÄrÐrJrJrJrKr s²ø üñ5   rc@s,eZdZdZdZdZdZdd„Zdd„Zd S) ÚESP32StubLoaderz7Access class for ESP32 stub loader, runs on top of ROM.i@rTcCs,|j|_|j|_|j|_|j|_| ¡dSrR)Úsecure_download_modeÚ_portÚ_trace_enabledÚcacherÌ)rEÚ rom_loaderrJrJrKÚ__init__�s  zESP32StubLoader.__init__cCst ||¡dSrR)rrÐ)rErÍrJrJrKrЈszESP32StubLoader.change_baudN) rÑrÒrÓrÔÚFLASH_WRITE_SIZErÝrÖrórÐrJrJrJrKrízs rí) r™rÊÚloaderrÚutilrrrríÚ STUB_CLASSrJrJrJrKÚ<module>s o 
10,381
Python
.pyt
75
136.373333
886
0.504657
OLIMEX/RVPC
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,712
train_mri2pet.py
ai-med_PASTA/train_mri2pet.py
import argparse import os from src.diffusion.gaussian_diffusion import GaussianDiffusion, ModelMeanType, ModelVarType, LossType from src.diffusion.respace import * from src.trainer.trainer import Trainer from src.model.unet import UNetModel from src.utils.utils import * OBJECTIVE = {'PREVIOUS_X': ModelMeanType.PREVIOUS_X, 'START_X': ModelMeanType.START_X, 'EPSILON': ModelMeanType.EPSILON, 'VELOCITY': ModelMeanType.VELOCITY} MODEL_VAR_TYPE = {'LEARNED': ModelVarType.LEARNED, 'FIXED_SMALL': ModelVarType.FIXED_SMALL, 'FIXED_LARGE': ModelVarType.FIXED_LARGE, 'LEARNED_RANGE': ModelVarType.LEARNED_RANGE} LOSS_TYPE = {'l1': LossType.MAE, 'l2': LossType.MSE} config_file = 'pasta_mri2pet.yaml' config_root = '/home/yitong/PASTA/src/config' # config_root = './PASTA/src/config' config_path = os.path.join(config_root, config_file) def main(): args = load_config_from_yaml(config_path) args_dict = args.__dict__ if not os.path.exists(args_dict['results_folder']): os.makedirs(args_dict['results_folder']) list_of_dict = [ f'{key} : {args_dict[key]}' for key in args_dict ] if not args_dict['eval_mode']: with open(os.path.join(args_dict['results_folder'], '_hyperparameters.yaml'), 'w') as data: [data.write(f'{st}\n') for st in list_of_dict] model = UNetModel( image_size = args.image_size, in_channels = args.model_in_channels, model_channels = args.unet_dim, out_channels = args.out_channels_model, num_res_blocks = args.num_res_blocks, attention_resolutions = args.attention_resolutions, # [16], num_heads = args.num_heads, channel_mult = args.unet_dim_mults, resblock_updown = args.resblock_updown, dims=args.dims, dropout = args.dropout, use_fp16 = False, use_scale_shift_norm = True, use_condition = True, use_time_condition = args.use_time_condition, cond_emb_channels = args.cond_emb_channels, tab_cond_dim = args.tab_cond_dim, use_tabular_cond = args.use_tabular_cond_model, with_attention = args.with_attention, cond_apply_method = args.cond_apply_method, ) encoder = UNetModel( image_size = args.image_size, in_channels = args.encoder_in_channels, model_channels = args.unet_dim, out_channels = args.out_channels_encoder, num_res_blocks = args.num_res_blocks, attention_resolutions = args.attention_resolutions, # [16], num_heads = args.num_heads, channel_mult = args.unet_dim_mults, resblock_updown = args.resblock_updown, dims=args.dims, dropout = args.dropout, use_fp16 = False, use_scale_shift_norm = True, use_condition = True, use_time_condition = args.use_time_condition, tab_cond_dim = args.tab_cond_dim, use_tabular_cond = args.use_tabular_cond_encoder, with_attention = args.with_attention, cond_apply_method = args.cond_apply_method, ) # spaced diffusion for ddim diffusion = SpacedDiffusion( use_timesteps = space_timesteps(args.timesteps, args.timestep_respacing), model = model, encoder = encoder, beta_schedule=args.beta_schedule, timesteps=args.timesteps, model_mean_type = OBJECTIVE[args.objective], model_var_type = MODEL_VAR_TYPE[args.model_var_type], loss_type = LOSS_TYPE[args.loss_type], gen_type = args.gen_type, use_fp16 = False, condition = args.condition, reconstructed_loss = args.reconstructed_loss, recon_weight = args.recon_weight, rescale_intensity = args.rescale_intensity, ) trainer = Trainer( diffusion, folder = args.data_dir, input_slice_channel = args.input_slice_channel, train_batch_size = args.train_batch_size, train_lr = args.train_lr, train_num_steps = args.train_num_steps, # total training steps save_and_sample_every = args.save_and_sample_every, # every n steps, save checkpoint & sample generative images num_samples = args.num_samples, gradient_accumulate_every = args.gradient_accumulate_every, # gradient accumulation steps ema_decay = args.ema_decay, # exponential moving average decay amp = args.amp, # turn on mixed precision fp16 = args.fp16, calculate_fid = args.calculate_fid, # whether to calculate fid during training dataset = args.dataset, # dataset name image_direction = args.image_direction, num_slices = args.num_slices, tabular_cond = args.tabular_cond, results_folder = args.results_folder, resume = args.resume, pretrain = args.pretrain, test_batch_size = args.test_batch_size, eval_mode = args.eval_mode, eval_dataset = args.eval_dataset, eval_resolution = args.eval_resolution, model_cycling = args.model_cycling, ROI_mask = args.ROI_mask, dx_labels = args.dx_labels, ) if trainer.eval_mode: if args.synthesis: synth_folder = os.path.join(trainer.results_folder, 'syn_pet') eval_model = os.path.join(trainer.results_folder, 'model.pt') trainer.evaluate(eval_model, synth_folder, synthesis=True, synthesis_folder = synth_folder, get_ROI_loss=True) else: eval_folder = os.path.join(trainer.results_folder, 'eval') eval_model = os.path.join(trainer.results_folder, 'model.pt') trainer.evaluate(eval_model, eval_folder) else: trainer.train() if __name__ == "__main__": set_seed_everywhere(666) main()
5,818
Python
.py
126
38.349206
177
0.649797
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,713
ssim.py
ai-med_PASTA/src/evals/ssim.py
import torch import torch.nn.functional as F from torch.autograd import Variable import numpy as np from math import exp def gaussian(window_size, sigma): gauss = torch.Tensor([exp(-(x - window_size//2)**2/float(2*sigma**2)) for x in range(window_size)]) return gauss/gauss.sum() def create_window(window_size, channel): _1D_window = gaussian(window_size, 1.5).unsqueeze(1) _2D_window = _1D_window.mm(_1D_window.t()).float().unsqueeze(0).unsqueeze(0) window = Variable(_2D_window.expand(channel, 1, window_size, window_size).contiguous()) return window def create_window_3D(window_size, channel): _1D_window = gaussian(window_size, 1.5).unsqueeze(1) _2D_window = _1D_window.mm(_1D_window.t()) _3D_window = _1D_window.mm(_2D_window.reshape(1, -1)).reshape(window_size, window_size, window_size).float().unsqueeze(0).unsqueeze(0) window = Variable(_3D_window.expand(channel, 1, window_size, window_size, window_size).contiguous()) return window def _ssim(img1, img2, window, window_size, channel, size_average = True): mu1 = F.conv2d(img1, window, padding = window_size//2, groups = channel) mu2 = F.conv2d(img2, window, padding = window_size//2, groups = channel) mu1_sq = mu1.pow(2) mu2_sq = mu2.pow(2) mu1_mu2 = mu1*mu2 sigma1_sq = F.conv2d(img1*img1, window, padding = window_size//2, groups = channel) - mu1_sq sigma2_sq = F.conv2d(img2*img2, window, padding = window_size//2, groups = channel) - mu2_sq sigma12 = F.conv2d(img1*img2, window, padding = window_size//2, groups = channel) - mu1_mu2 C1 = 0.01**2 C2 = 0.03**2 ssim_map = ((2*mu1_mu2 + C1)*(2*sigma12 + C2))/((mu1_sq + mu2_sq + C1)*(sigma1_sq + sigma2_sq + C2)) if size_average: return ssim_map.mean() else: return ssim_map.mean(1).mean(1).mean(1) def _ssim_3D(img1, img2, window, window_size, channel, size_average = True): mu1 = F.conv3d(img1, window, padding = window_size//2, groups = channel) mu2 = F.conv3d(img2, window, padding = window_size//2, groups = channel) mu1_sq = mu1.pow(2) mu2_sq = mu2.pow(2) mu1_mu2 = mu1*mu2 sigma1_sq = F.conv3d(img1*img1, window, padding = window_size//2, groups = channel) - mu1_sq sigma2_sq = F.conv3d(img2*img2, window, padding = window_size//2, groups = channel) - mu2_sq sigma12 = F.conv3d(img1*img2, window, padding = window_size//2, groups = channel) - mu1_mu2 C1 = 0.01**2 C2 = 0.03**2 ssim_map = ((2*mu1_mu2 + C1)*(2*sigma12 + C2))/((mu1_sq + mu2_sq + C1)*(sigma1_sq + sigma2_sq + C2)) if size_average: return ssim_map.mean() else: return ssim_map.mean(1).mean(1).mean(1) class SSIM(torch.nn.Module): def __init__(self, window_size = 11, size_average = True): super(SSIM, self).__init__() self.window_size = window_size self.size_average = size_average self.channel = 1 self.window = create_window(window_size, self.channel) def forward(self, img1, img2): (_, channel, _, _) = img1.size() if channel == self.channel and self.window.data.type() == img1.data.type(): window = self.window else: window = create_window(self.window_size, channel) if img1.is_cuda: window = window.cuda(img1.get_device()) window = window.type_as(img1) self.window = window self.channel = channel return _ssim(img1, img2, window, self.window_size, channel, self.size_average) class SSIM3D(torch.nn.Module): def __init__(self, window_size = 11, size_average = True): super(SSIM3D, self).__init__() self.window_size = window_size self.size_average = size_average self.channel = 1 self.window = create_window_3D(window_size, self.channel) def forward(self, img1, img2): (_, channel, _, _, _) = img1.size() if channel == self.channel and self.window.data.type() == img1.data.type(): window = self.window else: window = create_window_3D(self.window_size, channel) if img1.is_cuda: window = window.cuda(img1.get_device()) window = window.type_as(img1) self.window = window self.channel = channel return _ssim3D(img1, img2, window, self.window_size, channel, self.size_average) def ssim(img1, img2, window_size = 11, size_average = True): (_, channel, _, _) = img1.size() window = create_window(window_size, channel) if img1.is_cuda: window = window.cuda(img1.get_device()) window = window.type_as(img1) return _ssim(img1, img2, window, window_size, channel, size_average) def ssim3D(img1, img2, window_size = 11, size_average = True): (_, channel, _, _, _) = img1.size() window = create_window_3D(window_size, channel) if img1.is_cuda: window = window.cuda(img1.get_device()) window = window.type_as(img1) return _ssim_3D(img1, img2, window, window_size, channel, size_average)
5,155
Python
.py
103
42.300971
138
0.635829
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,714
dataset.py
ai-med_PASTA/src/datasets/dataset.py
import h5py import torch from torch import nn import torch.nn.functional as F from torch.utils.data import Dataset from torchvision import transforms as T, utils from tqdm import tqdm import pandas as pd from src.utils.data_utils import get_neighboring_slices, multislice_data_minimal_process, \ get_3d_image_transform, crop_minimally_keep_ratio, rescale_intensity, rescale_intensity_3D, \ resample_and_reshape, process_tabular_data, data_minimal_process, CropOrPad_3D import nibabel as nib import numpy as np import pandas as pd import os import logging LOG = logging.getLogger(__name__) # constants DIAGNOSIS_MAP = {"CN": 0, "Dementia": 1, "AD": 1, "MCI": 2} DIAGNOSIS_MAP_binary = {"CN": 0, "AD": 1, "Dementia": 1} # dataset class SlicedScanMRI2PETDataset(Dataset): def __init__( self, resolution = None, mri_root_path = '/path/to/mri', pet_root_path = '/path/to/pet', data_path = None, output_dim = 1, direction = 'coronal', standardized_tabular = True, classes=None, # 'binary' or 'multi' (with MCI) random_crop=False, random_flip=False, random_affine=False, resample_mri=False, dx_labels = ['CN', 'MCI', 'Dementia'], ): super().__init__() self.resolution = resolution self.mri_root_path = mri_root_path self.pet_root_path = pet_root_path self.data_path = data_path self.output_dim = output_dim self.direction = direction self.standardized_tabular = standardized_tabular self.random_crop = random_crop self.random_flip = random_flip self.random_affine = random_affine self.with_label = classes self.resample_mri = resample_mri self.dx_labels = dx_labels self._load() def _load(self): mri_data = [] pet_data = [] diagnosis = [] tabular_data = [] mri_uid = [] PET_shape = (113, 137, 113) MRI_shape = (113, 137, 113) if self.data_path is not None and 'h5' in self.data_path: print('loaded from h5 file') with h5py.File(self.data_path, mode='r') as file: for name, group in tqdm(file.items(), total=len(file)): if name == "stats": self.tabular_mean = group["tabular/mean"][:] self.tabular_std = group["tabular/stddev"][:] else: if group.attrs['DX'] not in self.dx_labels: continue if self.resample_mri: _raw_mri_data = group['MRI/T1/data'][:] _resampled_mri_data = resample_and_reshape(_raw_mri_data, (1.5, 1.5, 1.5), PET_shape) input_mri_data = _resampled_mri_data MRI_shape = PET_shape assert input_mri_data.shape == PET_shape else: input_mri_data = group['MRI/T1/data'][:] _pet_data = group['PET/FDG/data'][:] _mri_data = input_mri_data _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) else: print('loaded from: ', self.mri_root_path, self.pet_root_path) mri_id = os.listdir(self.mri_root_path) mri_input = [os.path.join(self.mri_root_path, i, 'mri.nii.gz') for i in mri_id] pet_input = [os.path.join(self.pet_root_path, i[:-8], f'pet_fdg.nii.gz') for i in mri_id] mri_data = [nib.load(i).get_fdata() for i in mri_input] pet_data = [nib.load(i).get_fdata() for i in pet_input] csv_info = pd.read_csv('data_info.csv') diagnosis = [csv_info.loc[csv_info["IMAGEUID"] == i]['DX'].values[0] for i in mri_id] tabular_data = [csv_info.loc[csv_info["IMAGEUID"] == i]['TAB'].values[0] for i in mri_id] mri_uid = mri_id self.len_data = len(pet_data) self._image_data_mri = mri_data self._image_data_pet = pet_data self._tabular_data = tabular_data self._mri_uid = mri_uid LOG.info("DATASET: %s", self.data_path if self.data_path is not None else self.mri_root_path) LOG.info("SAMPLES: %d", self.len_data) # if self.with_label is not None: labels, counts = np.unique(diagnosis, return_counts=True) LOG.info("Classes: %s", pd.Series(counts, index=labels)) if self.with_label == 'binary': self._diagnosis = [DIAGNOSIS_MAP_binary[d] for d in diagnosis] elif self.with_label == 'multi': self._diagnosis = [DIAGNOSIS_MAP[d] for d in diagnosis] else: self._diagnosis = [DIAGNOSIS_MAP[d] for d in diagnosis] def __len__(self): return self.len_data def __getitem__(self, idx): MRI_shape = self.resolution PET_shape = self.resolution mri_scan = self._image_data_mri[idx] pet_scan = self._image_data_pet[idx] tabular_data = self._tabular_data[idx] mri_uid = self._mri_uid[idx] mri_scan = rescale_intensity_3D(mri_scan) pet_scan = rescale_intensity_3D(pet_scan) mri_scan = CropOrPad_3D(mri_scan, MRI_shape) pet_scan = CropOrPad_3D(pet_scan, PET_shape) if self.standardized_tabular: tabular_data = (tabular_data - self.tabular_mean) / self.tabular_std tabular_data = process_tabular_data(tabular_data) mri_scan_list = [] pet_scan_list = [] data_transform = T.Compose([ T.ToTensor(), # T.CenterCrop((self.resolution[0], self.resolution[1])) if self.resolution is not None else nn.Identity(), # T.Resize((self.resolution[0], self.resolution[1]), antialias=True) if self.resolution is not None else nn.Identity(), T.RandomVerticalFlip() if self.random_flip else nn.Identity(), T.RandomAffine(180, translate=(0.3, 0.3)) if self.random_affine else nn.Identity(), ]) if self.direction == 'coronal': for i in range(MRI_shape[1]): if self.output_dim > 1: _mri_data = get_neighboring_slices(self.output_dim, self.direction, i, mri_scan) _pet_data = get_neighboring_slices(self.output_dim, self.direction, i, pet_scan) _pet_data = np.nan_to_num(_pet_data, copy=False) _mri_data = multislice_data_minimal_process(self.output_dim, self.resolution, _mri_data, data_transform) _pet_data = multislice_data_minimal_process(self.output_dim, self.resolution, _pet_data, data_transform) else: _pet_data = pet_scan[:, i, :] _mri_data = mri_scan[:, i, :] _pet_data = np.nan_to_num(_pet_data, copy=False) _mri_data = data_minimal_process(self.resolution, _mri_data, data_transform) _pet_data = data_minimal_process(self.resolution, _pet_data, data_transform) mri_scan_list.append(_mri_data) pet_scan_list.append(_pet_data) elif self.direction == 'sagittal': for i in range(MRI_shape[0]): if self.output_dim > 1: _mri_data = get_neighboring_slices(self.output_dim, self.direction, i, mri_scan) _pet_data = get_neighboring_slices(self.output_dim, self.direction, i, pet_scan) _pet_data = np.nan_to_num(_pet_data, copy=False) _mri_data = multislice_data_minimal_process(self.output_dim, self.resolution, _mri_data, data_transform) _pet_data = multislice_data_minimal_process(self.output_dim, self.resolution, _pet_data, data_transform) else: _pet_data = pet_scan[i, :, :] _mri_data = mri_scan[i, :, :] _pet_data = np.nan_to_num(_pet_data, copy=False) _mri_data = data_minimal_process(self.resolution, _mri_data, data_transform) _pet_data = data_minimal_process(self.resolution, _pet_data, data_transform) mri_scan_list.append(_mri_data) pet_scan_list.append(_pet_data) elif self.direction == 'axial': for i in range(MRI_shape[2]): if self.output_dim > 1: _mri_data = get_neighboring_slices(self.output_dim, self.direction, i, mri_scan) _pet_data = get_neighboring_slices(self.output_dim, self.direction, i, pet_scan) _pet_data = np.nan_to_num(_pet_data, copy=False) _mri_data = multislice_data_minimal_process(self.output_dim, self.resolution, _mri_data, data_transform) _pet_data = multislice_data_minimal_process(self.output_dim, self.resolution, _pet_data, data_transform) else: _pet_data = pet_scan[:, :, i] _mri_data = mri_scan[:, :, i] _pet_data = np.nan_to_num(_pet_data, copy=False) _mri_data = data_minimal_process(self.resolution, _mri_data, data_transform) _pet_data = data_minimal_process(self.resolution, _pet_data, data_transform) mri_scan_list.append(_mri_data) pet_scan_list.append(_pet_data) label = self._diagnosis[idx] return mri_scan_list, pet_scan_list, label, tabular_data, mri_uid class MRI2PET_2_5D_Dataset(Dataset): def __init__( self, resolution = None, mri_root_path = '/path/to/mri', pet_root_path = '/path/to/pet', data_path = None, output_dim = 3, direction = 'axial', num_slices = 'all', standardized_tabular = True, classes=None, # 'binary' or 'multi' (with MCI) random_crop=False, random_flip=False, random_affine=False, resample_mri=False, ROI_mask = None, dx_labels = ['CN', 'Dementia', 'MCI'], ): super().__init__() self.resolution = resolution self.mri_root_path = mri_root_path self.pet_root_path = pet_root_path self.data_path = data_path self.output_dim = output_dim self.direction = direction self.num_slices = num_slices self.standardized_tabular = standardized_tabular self.random_crop = random_crop self.random_flip = random_flip self.random_affine = random_affine self.with_label = classes self.resample_mri = resample_mri self.ROI_mask = ROI_mask self.dx_labels = dx_labels self._load() def _load(self): mri_data = [] pet_data = [] diagnosis = [] tabular_data = [] slice_index = [] mri_uid = [] PET_shape = (113, 137, 113) MRI_shape = (113, 137, 113) flag = 0 if 'h5' in self.data_path: print('loaded from h5 file') with h5py.File(self.data_path, mode='r') as file: for name, group in tqdm(file.items(), total=len(file)): if name == "stats": self.tabular_mean = group["tabular/mean"][:] self.tabular_std = group["tabular/stddev"][:] else: if group.attrs['DX'] not in self.dx_labels: continue if self.resample_mri: _raw_mri_data = group['MRI/T1/data'][:] _resampled_mri_data = resample_and_reshape(_raw_mri_data, (1.5, 1.5, 1.5), PET_shape) input_mri_data = _resampled_mri_data MRI_shape = PET_shape assert input_mri_data.shape == PET_shape input_pet_data = group['PET/FDG/data'][:] else: input_mri_data = group['MRI/T1/data'][:] input_pet_data = group['PET/FDG/data'][:] if self.direction == 'coronal': max_slice_index = PET_shape[1] - 1 if self.num_slices == 1: _mri_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[1] // 2 + 1, input_mri_data) _pet_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[1] // 2 + 1, input_pet_data) _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) slice_index.append(PET_shape[1] // 2 + 1) elif self.num_slices == 'all': for i in range(PET_shape[1]): # get the ith slice's neighboring slices to form the image with self.output_dim channels _mri_data = get_neighboring_slices(self.output_dim, self.direction, i, input_mri_data) _pet_data = get_neighboring_slices(self.output_dim, self.direction, i, input_pet_data) _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) if not np.any(_pet_data) or not np.any(_mri_data): continue mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) slice_index.append(i) else: for i in range(-self.num_slices // 2, self.num_slices // 2): _mri_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[1] // 2 + 1 + i, input_mri_data) _pet_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[1] // 2 + 1 + i, input_pet_data) _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) if not np.any(_pet_data) or not np.any(_mri_data): continue mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) slice_index.append(PET_shape[1] // 2 + 1 + i) elif self.direction == 'sagittal': max_slice_index = PET_shape[0] - 1 if self.num_slices == 1: _mri_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[0] // 2 + 1, input_mri_data) _pet_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[0] // 2 + 1, input_pet_data) _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) slice_index.append(PET_shape[0] // 2 + 1) elif self.num_slices == 'all': for i in range(PET_shape[0]): _mri_data = get_neighboring_slices(self.output_dim, self.direction, i, input_mri_data) _pet_data = get_neighboring_slices(self.output_dim, self.direction, i, input_pet_data) _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) if not np.any(_pet_data) or not np.any(_mri_data): continue mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) slice_index.append(i) else: for i in range(-self.num_slices // 2, self.num_slices // 2): _mri_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[0] // 2 + 1 + i, input_mri_data) _pet_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[0] // 2 + 1 + i, input_pet_data) _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) if not np.any(_pet_data) or not np.any(_mri_data): continue mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) slice_index.append(PET_shape[0] // 2 + 1 + i) elif self.direction == 'axial': max_slice_index = PET_shape[2] - 1 if self.num_slices == 1: _mri_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[2] // 2 + 1, input_mri_data) _pet_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[2] // 2 + 1, input_pet_data) _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) slice_index.append(PET_shape[2] // 2 + 1) elif self.num_slices == 'all': for i in range(PET_shape[2]): _mri_data = get_neighboring_slices(self.output_dim, self.direction, i, input_mri_data) _pet_data = get_neighboring_slices(self.output_dim, self.direction, i, input_pet_data) _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) if not np.any(_pet_data) or not np.any(_mri_data): continue mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) slice_index.append(i) else: for i in range(-self.num_slices // 2, self.num_slices // 2): _mri_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[2] // 2 + 1 + i, input_mri_data) _pet_data = get_neighboring_slices(self.output_dim, self.direction, PET_shape[2] // 2 + 1 + i, input_pet_data) _tabular_data = group['tabular'][:] _diagnosis = group.attrs['DX'] _pet_data = np.nan_to_num(_pet_data, copy=False) if not np.any(_pet_data) or not np.any(_mri_data): continue mri_data.append(_mri_data) pet_data.append(_pet_data) tabular_data.append(_tabular_data) diagnosis.append(_diagnosis) mri_uid.append(name) slice_index.append(PET_shape[2] // 2 + 1 + i) else: raise NotImplementedError self.len_data = len(pet_data) self._image_data_mri = mri_data self._image_data_pet = pet_data self._tabular_data = tabular_data self._slice_index = [float(i / max_slice_index) for i in slice_index] self._max_slice_index = max_slice_index self._mri_uid = mri_uid LOG.info("DATASET: %s", self.data_path) LOG.info("SAMPLES: %d", self.len_data) LOG.info("Input Shape: {}".format(mri_data[0].shape)) # if self.with_label is not None: labels, counts = np.unique(diagnosis, return_counts=True) LOG.info("Classes: %s", pd.Series(counts, index=labels)) if self.with_label == 'binary': self._diagnosis = [DIAGNOSIS_MAP_binary[d] for d in diagnosis] elif self.with_label == 'multi': self._diagnosis = [DIAGNOSIS_MAP[d] for d in diagnosis] else: self._diagnosis = [DIAGNOSIS_MAP[d] for d in diagnosis] if self.ROI_mask is not None: self._ROI_mask = nib.load(self.ROI_mask).get_fdata() print('Loaded ROI mask shape: ', self._ROI_mask.shape) assert PET_shape == self._ROI_mask.shape, ('ROI mask shape is not Input data shape', self._ROI_mask.shape, mri_data[0].shape) else: self._ROI_mask = None def __len__(self): return self.len_data def __getitem__(self, idx): mri_scan = self._image_data_mri[idx] pet_scan = self._image_data_pet[idx] tabular_data = self._tabular_data[idx] slice_index = self._slice_index[idx] assert slice_index <= 1 and slice_index >= 0, 'slice index should be normalized to [0, 1]' if self._ROI_mask is not None: roi_mask = get_neighboring_slices(self.output_dim, self.direction, int(slice_index * self._max_slice_index), self._ROI_mask) assert roi_mask.shape == mri_scan.shape, ('roi mask shape is not Input scan shape', roi_mask.shape, mri_scan.shape) loss_weight_mask = roi_mask.copy() loss_weight_mask[roi_mask == 0] = 1 loss_weight_mask[roi_mask == 1] = 10 else: loss_weight_mask = np.ones(mri_scan.shape) print('No ROI mask is used, loss weight mask is all ones') if self.standardized_tabular: tabular_data = (tabular_data - self.tabular_mean) / self.tabular_std tabular_data = process_tabular_data(tabular_data) data_transform = T.Compose([ T.ToTensor(), T.CenterCrop((self.resolution[0], self.resolution[1])) if self.resolution is not None else nn.Identity(), # T.Resize((self.resolution[0], self.resolution[1]), antialias=True) if self.resolution is not None else nn.Identity(), T.RandomVerticalFlip() if self.random_flip else nn.Identity(), T.RandomAffine(180, translate=(0.3, 0.3)) if self.random_affine else nn.Identity(), ]) processed_mri = np.zeros((self.output_dim, self.resolution[0], self.resolution[1])).astype(np.float32) processed_pet = np.zeros((self.output_dim, self.resolution[0], self.resolution[1])).astype(np.float32) processed_loss_weight_mask = np.zeros((self.output_dim, self.resolution[0], self.resolution[1])).astype(np.float32) for i in range(mri_scan.shape[0]): _mri_data = mri_scan[i, :, :] _pet_data = pet_scan[i, :, :] _loss_weight_mask = loss_weight_mask[i, :, :] _mri_data = data_minimal_process(self.resolution, _mri_data, data_transform) _pet_data = data_minimal_process(self.resolution, _pet_data, data_transform) _loss_weight_mask = data_minimal_process(self.resolution, _loss_weight_mask, data_transform) processed_mri[i, :, :] = _mri_data processed_pet[i, :, :] = _pet_data processed_loss_weight_mask[i, :, :] = _loss_weight_mask mri_scan = processed_mri pet_scan = processed_pet loss_weight_mask = processed_loss_weight_mask label = self._diagnosis[idx] mri_uid = self._mri_uid[idx] assert mri_scan.shape == (self.output_dim, self.resolution[0], self.resolution[1]), 'mri scan shape is not correct' assert pet_scan.shape == (self.output_dim, self.resolution[0], self.resolution[1]), 'pet scan shape is not correct' return mri_scan, pet_scan, label, tabular_data, slice_index, loss_weight_mask, mri_uid
27,826
Python
.py
465
39.503226
146
0.500521
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,715
trainer.py
ai-med_PASTA/src/trainer/trainer.py
import math from pathlib import Path import os import torch from torch import nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from torch.cuda.amp import autocast from torchvision import transforms as T, utils import torchio as tio from einops import rearrange, reduce, repeat from tqdm.auto import tqdm from ema_pytorch import EMA import nibabel as nib import numpy as np from accelerate import Accelerator from pytorch_fid.inception import InceptionV3 from pytorch_fid.fid_score import calculate_frechet_distance from torch.utils.tensorboard import SummaryWriter from src.datasets.dataset import * from src.utils.utils import * from src.evals.ssim import * from src.utils.data_utils import reconstruct_scan_from_2_5D_slices class Trainer(object): def __init__( self, diffusion_model, folder, *, input_slice_channel = 15, train_batch_size = 16, gradient_accumulate_every = 1, augment_horizontal_flip = False, train_lr = 1e-4, train_num_steps = 100000, ema_update_every = 10, ema_decay = 0.995, adam_betas = (0.9, 0.999), weight_decay = 1e-5, save_and_sample_every = 1000, num_samples = 16, results_folder = './results', amp = False, fp16 = True, split_batches = False, calculate_fid = False, inception_block_idx = 2048, dataset = None, image_direction = 'axial', # sagittal, axial, coronal num_slices = 1, model_cycling = False, tabular_cond = False, resume = None, pretrain = None, test_batch_size = 8, eval_mode = False, eval_dataset = 'ADNI', eval_resolution = [96, 112, 96], ROI_mask = None, dx_labels = ['CN', 'Dementia', 'MCI'], ): super().__init__() self.dataset = dataset self.fp16 = fp16 self.image_direction = image_direction self.input_slice_channel = input_slice_channel self.model_cycling = model_cycling self.tabular_cond = tabular_cond self.eval_mode = eval_mode self.eval_dataset = eval_dataset self.results_folder = results_folder self.ROI_mask = ROI_mask self.eval_resolution = eval_resolution if not eval_mode: self.writer = SummaryWriter(log_dir = results_folder + '/logs') # accelerator self.accelerator = Accelerator( split_batches = split_batches, mixed_precision = 'fp16' if fp16 else 'no' ) self.accelerator.native_amp = amp # model self.model = diffusion_model self.channels = diffusion_model.model.out_channels # try to load pretrianed model if pretrain: ignored_weights = ['input_blocks.0.0.weight', 'out.2.weight', 'out.2.bias'] self.load_pretrained_model(pretrain, ignored_weights) print('===load pretrained model successfully===') # InceptionV3 for fid-score computation self.inception_v3 = None if calculate_fid: assert inception_block_idx in InceptionV3.BLOCK_INDEX_BY_DIM block_idx = InceptionV3.BLOCK_INDEX_BY_DIM[inception_block_idx] self.inception_v3 = InceptionV3([block_idx]) self.inception_v3.to(self.device) # sampling and training hyperparameters assert has_int_squareroot(num_samples), 'number of samples must have an integer square root' self.num_samples = num_samples self.save_and_sample_every = save_and_sample_every self.batch_size = train_batch_size self.gradient_accumulate_every = gradient_accumulate_every self.train_num_steps = train_num_steps self.image_size = diffusion_model.model.image_size # dataset and dataloader if dataset == 'MRI2PET': if not eval_mode: train_data = folder + 'train.h5' valid_data = folder + 'valid.h5' self.ds = MRI2PET_2_5D_Dataset(self.image_size, data_path = train_data, output_dim=input_slice_channel, direction = image_direction, num_slices = num_slices, random_flip = False, random_affine = False, ROI_mask = ROI_mask, dx_labels = dx_labels) self.ds_valid = MRI2PET_2_5D_Dataset(self.image_size, data_path = valid_data, output_dim=input_slice_channel, direction = image_direction, num_slices = num_slices, random_flip = False, random_affine = False, dx_labels = dx_labels) self.dl_valid = DataLoader(self.ds_valid, batch_size = train_batch_size, shuffle = True, pin_memory = True, num_workers = 2, drop_last=False) else: if self.eval_dataset == 'ADNI': self.test_data = folder + 'test.h5' ### # use whole scan per iteration ds_test = SlicedScanMRI2PETDataset(eval_resolution, data_path = self.test_data, output_dim=input_slice_channel, direction = image_direction, random_flip=None, dx_labels = dx_labels) else: raise NotImplementedError self.dl_test = DataLoader(ds_test, batch_size = test_batch_size, shuffle = False, pin_memory = True, num_workers = 2, drop_last=False) else: raise NotImplementedError # for logging results in a folder periodically if self.accelerator.is_main_process: self.ema = EMA(diffusion_model, beta = ema_decay, update_every = ema_update_every) self.ema.to(self.device) if not eval_mode: dl = DataLoader(self.ds, batch_size = train_batch_size, shuffle = True, pin_memory = True, num_workers = 2, drop_last=False) dl = self.accelerator.prepare(dl) self.dl = dl # optimizer and scheduler self.opt = torch.optim.AdamW(diffusion_model.parameters(), lr = train_lr, betas = adam_betas, weight_decay = weight_decay) self.scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(self.opt, T_max=train_num_steps, eta_min=train_lr*0.1) self.results_folder = Path(results_folder) self.results_folder.mkdir(exist_ok = True) # step counter state self.step = 0 # prepare model, dataloader, optimizer with accelerator if resume: self.load(self.step, path = resume) print(f"resuming from model successfully") self.model, self.opt = self.accelerator.prepare(self.model, self.opt) print_model_size(self.model) @property def device(self): return self.accelerator.device def save(self, milestone, model_name = 'model.pt'): if not self.accelerator.is_local_main_process: return data = { 'step': self.step, 'model': self.accelerator.get_state_dict(self.model), 'opt': self.opt.state_dict(), 'ema': self.ema.state_dict(), 'scaler': self.accelerator.scaler.state_dict() if exists(self.accelerator.scaler) else None, } torch.save(data, str(self.results_folder / model_name)) def load(self, milestone = 0, path = None): accelerator = self.accelerator device = accelerator.device if path is not None: data = torch.load(path, map_location = device) else: data = torch.load(str(self.results_folder / f'model.pt'), map_location=device) model = self.accelerator.unwrap_model(self.model) msg = model.load_state_dict(data['model'], strict=False) print('======load pretrained model successfully========') print("missing keys:", msg.missing_keys) print("Unexpected keys:", msg.unexpected_keys) self.step = data['step'] msg_opt = self.opt.load_state_dict(data['opt']) if self.accelerator.is_main_process: msg_ema = self.ema.load_state_dict(data["ema"], strict=False) print("ema missing keys:", msg_ema.missing_keys) print("ema Unexpected keys:", msg_ema.unexpected_keys) if exists(self.accelerator.scaler) and exists(data['scaler']): self.accelerator.scaler.load_state_dict(data['scaler']) print('loaded model successfully from step:', self.step) def load_pretrained_model(self, path, ignore): accelerator = self.accelerator device = accelerator.device pretrained_model = torch.load(path, map_location = device) new_state_dict = {} for key, value in pretrained_model.items(): if key in ignore: continue new_key = 'model.' + key new_state_dict[new_key] = value model = self.accelerator.unwrap_model(self.model) msg = model.load_state_dict(new_state_dict, strict=False) print('======load pretrained model successfully========') print("missing keys:", msg.missing_keys) print("Unexpected keys:", msg.unexpected_keys) @torch.no_grad() def calculate_activation_statistics(self, samples): assert exists(self.inception_v3) self.inception_v3.eval() features = self.inception_v3(samples)[0] features = rearrange(features, '... 1 1 -> ...').cpu().numpy() mu = np.mean(features, axis = 0) sigma = np.cov(features, rowvar = False) return mu, sigma def fid_score(self, real_samples, fake_samples): if real_samples.shape[1] == 1: real_samples, fake_samples = map(lambda t: repeat(t, 'b 1 ... -> b c ...', c = 3), (real_samples, fake_samples)) min_batch = min(real_samples.shape[0], fake_samples.shape[0]) real_samples, fake_samples = map(lambda t: t[:min_batch], (real_samples, fake_samples)) m1, s1 = self.calculate_activation_statistics(real_samples) m2, s2 = self.calculate_activation_statistics(fake_samples) fid_value = calculate_frechet_distance(m1, s1, m2, s2) return fid_value def psnr(self, img1, img2): """ Args: img1: (n, c, h, w, l) """ v_max = 1. # (n,) min_batch = min(img1.shape[0], img2.shape[0]) img1, img2 = map(lambda t: t[:min_batch], (img1, img2)) mse = torch.mean((img1 - img2)**2, dim=[1, 2, 3]) return 20 * torch.log10(v_max / torch.sqrt(mse)) def train(self): accelerator = self.accelerator device = accelerator.device best_val_mae = 1000. best_val_ssim = 0. with tqdm(initial = self.step, total = self.train_num_steps, disable = not accelerator.is_main_process) as pbar: while self.step < self.train_num_steps: total_loss = 0. for _ in range(self.gradient_accumulate_every): data = next(iter(self.dl)) self.opt.zero_grad() with autocast(self.fp16, dtype=torch.float16): # with self.accelerator.autocast(): if self.dataset == 'MRI2PET' or self.dataset == 'GM2PET': _train_data = data mri_data, pet_data = _train_data[0], _train_data[1] mri_uid = _train_data[-1] cond_data = mri_data data_label = _train_data[2] if self.tabular_cond: tabular_data = _train_data[3] else: tabular_data = None slice_index = _train_data[4] loss_weight_mask = _train_data[5] model_output = self.model(pet_data, cond = cond_data, tab_cond = tabular_data, loss_weight_mask = loss_weight_mask) loss_dif = model_output['loss'].mean() self.writer.add_scalar('train/train_loss_dif', loss_dif, self.step) loss = loss_dif if self.model_cycling: # first cycle, part two, from PET to MRI synthetic_pet = model_output['model_output'] model_output_cycle = self.model(mri_data, cond = synthetic_pet, tab_cond = tabular_data, model_cycle = True, loss_weight_mask = loss_weight_mask) loss_cycle = model_output_cycle['loss'].mean() self.writer.add_scalar('train/train_loss_cycle', loss_cycle, self.step) loss += loss_cycle # second cycle, part one, from PET to MRI model_output_r2 = self.model(mri_data, cond = pet_data, tab_cond = tabular_data, model_cycle = True, loss_weight_mask = loss_weight_mask) loss_cycle_r2 = model_output_r2['loss'].mean() loss += loss_cycle_r2 # second cycle, part two, from MRI to PET synthetic_mri = model_output_r2['model_output'] model_output_cycle_r2 = self.model(pet_data, cond = synthetic_mri, tab_cond = tabular_data, model_cycle = False, loss_weight_mask = loss_weight_mask) loss += model_output_cycle_r2['loss'].mean() loss = loss / self.gradient_accumulate_every total_loss += loss.item() else: data = next(self.dl).to(device) loss = self.model(data) loss = loss / self.gradient_accumulate_every total_loss += loss.item() self.accelerator.backward(loss) accelerator.clip_grad_norm_(self.model.parameters(), 1.0) desc = f'loss: {loss_dif:.6f}' pbar.set_description(desc) self.writer.add_scalar('train/train_loss', total_loss, self.step) accelerator.wait_for_everyone() self.opt.step() self.scheduler.step() accelerator.wait_for_everyone() self.step += 1 if accelerator.is_main_process: self.ema.update() if self.step != 0 and self.step % self.save_and_sample_every == 0: self.ema.ema_model.eval() all_images_list = [] data = [] if self.dataset == 'MRI2PET': valid_loss = 0. val_iter = 0 for valid_data in self.dl_valid: _valid_data = valid_data valid_data_mri, valid_data_pet = _valid_data[0], _valid_data[1] valid_cond_data = valid_data_mri mri_uid = _valid_data[-1] if self.tabular_cond: tabular_data = _valid_data[3] tabular_data = tabular_data.to(device) else: tabular_data = None slice_index = _valid_data[4] batches = valid_data_mri.shape[0] with torch.no_grad(): milestone = self.step // self.save_and_sample_every loss = self.ema.ema_model(valid_data_pet.to(device), cond = valid_cond_data.to(device), tab_cond = tabular_data)['loss'].mean() valid_loss = loss print(f'valid loss: {valid_loss:.6f}') # save validation loss to tensorboard self.writer.add_scalar('val/val_loss', valid_loss, self.step) print('valid_pet_shape:', valid_data_pet.shape) sample_pet = self.ema.ema_model.sample(shape = valid_data_pet.shape, cond = valid_cond_data.to(device), tab_cond = tabular_data) print('sample_pet_shape:', sample_pet.shape) all_images_list.append(sample_pet) data.append(valid_data_pet) if val_iter == 10: break val_iter += 1 else: with torch.no_grad(): milestone = self.step // self.save_and_sample_every # batches = num_to_groups(self.num_samples, self.batch_size) batches = [data.shape[0]] all_images_list = list(map(lambda n: self.ema.ema_model.sample(batch_size=n), batches)) data = [img.reshape(img.shape[0]*img.shape[1], img.shape[2], img.shape[3]) for img in data] all_images_list = [img.reshape(img.shape[0]*img.shape[1], img.shape[2], img.shape[3]) for img in all_images_list] data = torch.cat(data, dim = 0).unsqueeze(1) all_images = torch.cat(all_images_list, dim = 0).unsqueeze(1) print('data_shape:', data.shape) print('all_images_shape:', all_images.shape) recon_loss_l2 = F.mse_loss(all_images, data.to(device)) print(f'valid recon L2 loss: {recon_loss_l2:.5f}') recon_loss_l1 = F.l1_loss(all_images, data.to(device)) print(f'valid recon L1 loss: {recon_loss_l1:.5f}') with open(str(self.results_folder / f'scores.txt'), 'a') as f: f.write('\n') f.write(f'milestone: {milestone}') f.write('\n') f.write(f'valid recon L1 loss: {recon_loss_l1:.5f}') f.write('\n') f.write(f'valid recon L2 loss: {recon_loss_l2:.5f}') utils.save_image(all_images, str(self.results_folder / f'sample-{milestone}.png'), nrow = int(math.sqrt(self.num_samples))) if self.dataset == 'MRI2PET' or self.dataset == 'GM2PET': utils.save_image(data, str(self.results_folder / f'real-{milestone}.png'), nrow = int(math.sqrt(self.num_samples))) self.save(milestone) real_samples = torch.nan_to_num(data) fake_samples = torch.nan_to_num(all_images) if exists(self.inception_v3): fid_score = self.fid_score(real_samples.to(device), fake_samples.to(device)) accelerator.print(f'fid_score: {fid_score}') with open(str(self.results_folder / f'scores.txt'), 'a') as f: f.write('\n') f.write(f'fid_score: {fid_score}') psnr_score = self.psnr(data.to(device), all_images.to(device)).mean().detach().cpu().numpy() accelerator.print(f'psnr_score: {str(psnr_score)}') with open(str(self.results_folder / f'scores.txt'), 'a') as f: f.write('\n') f.write(f'psnr_score: {str(psnr_score)}') ssim_score = ssim(data.to(device), all_images.to(device)).detach().cpu().numpy() accelerator.print(f'ssim_score: {str(ssim_score)}') with open(str(self.results_folder / f'scores.txt'), 'a') as f: f.write('\n') f.write(f'ssim_score: {str(ssim_score)}') f.write('\n') mse_score = (data.to(device) - all_images.to(device)).pow(2).mean(dim=[1, 2, 3]) print(f'mse_score: {str(mse_score)}') if recon_loss_l1 - best_val_mae < 0.001 and ssim_score - best_val_ssim > 0.001: best_val_mae = recon_loss_l1 best_val_ssim = ssim_score print('best val mae:', best_val_mae.item()) self.save(milestone, model_name = 'best_val_model.pt') with open(str(self.results_folder / f'scores.txt'), 'a') as f: f.write('\n') f.write(f'************Best val model, milestone: {milestone}*************') f.write('\n') pbar.update(1) accelerator.print('training complete') @torch.no_grad() def evaluate(self, checkpoint, evaluate_folder, synthesis=False, synthesis_folder=None, get_ROI_loss=False): self.evaluate_folder = Path(evaluate_folder) self.evaluate_folder.mkdir(exist_ok = True) if synthesis: assert synthesis_folder is not None, 'synthesis_folder is None' syn_folder = Path(synthesis_folder) syn_folder.mkdir(exist_ok = True) if get_ROI_loss: assert self.ROI_mask is not None, 'ROI_mask is None' self.ROI_mask = nib.load(self.ROI_mask).get_fdata() self.ROI_mask = tio.CropOrPad(self.eval_resolution)(self.ROI_mask[np.newaxis, ...]).squeeze(0) print('use ROI loss, ROI_mask_shape:', self.ROI_mask.shape) roi_losses = [] data = torch.load(checkpoint, map_location = self.device) msg = self.model.load_state_dict(data['model'], strict=False) print('======load pretrained model successfully========') print("missing keys:", msg.missing_keys) print("Unexpected keys:", msg.unexpected_keys) self.step = data['step'] msg_ema = self.ema.load_state_dict(data["ema"], strict=False) print("ema missing keys:", msg_ema.missing_keys) print("ema Unexpected keys:", msg_ema.unexpected_keys) print('loaded model successfully from:', checkpoint) self.model.eval() self.ema.ema_model.eval() if self.dataset == 'MRI2PET': test_loss = 0. flag = 0 real_images_list = [] sample_images_list = [] error_map_list = [] averaged_sample_images_list = [] LABEL_MAP = {0: 'CN', 1: 'AD', 2: 'MCI'} for test_data in self.dl_test: _test_data = test_data test_data_mri, test_data_pet = _test_data[0], _test_data[1] dx_label = _test_data[2] mri_uid = _test_data[-1] if self.tabular_cond: tabular_data = _test_data[3] tabular_data = tabular_data.to(self.device) else: tabular_data = None slices_per_sample_list = [] GT_images_list = [] if self.model_cycling: slices_per_mri_sample_list = [] GT_mri_images_list = [] for slice_num in range(len(test_data_mri)): mri_slice = test_data_mri[slice_num] pet_slice = test_data_pet[slice_num] mri_slice = mri_slice.to(self.device) pet_slice = pet_slice.to(self.device) cond_slice = mri_slice with torch.no_grad(): sample_pet = self.ema.ema_model.sample(shape = pet_slice.shape, cond = cond_slice, tab_cond = tabular_data) if not synthesis: test_loss = torch.abs(sample_pet - pet_slice) print(f'****** Slice {slice_num}: *********') print(f'=========== MRI -> PET, loss(GT PET, Syn PET): =============') for batch in range(test_loss.shape[0]): batch_loss = test_loss[batch].mean() label = LABEL_MAP[int(dx_label[batch].item())] print(f'{label}: {batch_loss:.6f} | ') # if model_cycling then calculate the PET -> MRI loss if self.model_cycling and not synthesis: model_output = self.ema.ema_model(cond_slice, cond = sample_pet, tab_cond = tabular_data, model_cycle = True) cycle_loss = model_output['loss'] print(f'========== PET -> MRI, loss(GT MRI, Syn MRI): ==========') for batch in range(cycle_loss.shape[0]): batch_loss = cycle_loss[batch].mean() label = LABEL_MAP[int(dx_label[batch].item())] print(f'{label}: {batch_loss:.6f} | ') unnormalize = unnormalize_to_zero_to_one if self.ema.ema_model.rescale_intensity else identity slices_per_mri_sample_list.append(unnormalize(model_output['model_output'])) slices_per_sample_list.append(sample_pet) if self.input_slice_channel > 1: sample_pet = sample_pet[:, self.input_slice_channel // 2, ...].unsqueeze(1) pet_slice = pet_slice[:, self.input_slice_channel // 2, ...].unsqueeze(1) sample_images_list.append(sample_pet) real_images_list.append(pet_slice) GT_images_list.append(pet_slice.squeeze(1)) if self.model_cycling and not synthesis: mri_slice = mri_slice[:, self.input_slice_channel // 2, ...].unsqueeze(1) GT_mri_images_list.append(mri_slice.squeeze(1)) else: sample_images_list.append(sample_pet) real_images_list.append(pet_slice) GT_images_list.append(pet_slice) if self.model_cycling and not synthesis: GT_mri_images_list.append(mri_slice) if flag == 0 and not synthesis: # error map become the difference between generated and real images error_map = sample_pet.to(self.device) - pet_slice.to(self.device) error_map_list.append(error_map) error_map_label = _test_data[2] if self.input_slice_channel > 1: slices_per_sample_list = reconstruct_scan_from_2_5D_slices(slices_per_sample_list) for slice_per_sample in slices_per_sample_list: averaged_sample_images_list.append(slice_per_sample.unsqueeze(1)) if self.model_cycling and not synthesis: slices_per_mri_sample_list = reconstruct_scan_from_2_5D_slices(slices_per_mri_sample_list) else: averaged_sample_images_list = sample_images_list axis_map = {'coronal': -2, 'sagittal': -3, 'axial': -1} whole_pet_sample = np.stack([slice_tensor.cpu().numpy() for slice_tensor in slices_per_sample_list], axis=axis_map[self.image_direction]) whole_GT_pet = np.stack([slice_tensor.cpu().numpy() for slice_tensor in GT_images_list], axis=axis_map[self.image_direction]) assert whole_pet_sample.shape == whole_GT_pet.shape, (whole_pet_sample.shape, whole_GT_pet.shape) if self.model_cycling and not synthesis: whole_mri_sample = np.stack([slice_tensor.cpu().numpy() for slice_tensor in slices_per_mri_sample_list], axis=axis_map[self.image_direction]) whole_GT_mri = np.stack([slice_tensor.cpu().numpy() for slice_tensor in GT_mri_images_list], axis=axis_map[self.image_direction]) assert whole_mri_sample.shape == whole_GT_mri.shape, (whole_mri_sample.shape, whole_GT_mri.shape) affine = np.array([ [1.5, 0, 0, 0], [0, 1.5, 0, 0], [0, 0, 1.5, 0], [0, 0, 0, 1] ]) for slice_batch in range(whole_pet_sample.shape[0]): img_label = str(LABEL_MAP[int(dx_label[slice_batch].detach().cpu().numpy())]) _mri_uid = str(mri_uid[slice_batch]) if synthesis: _L1_loss = np.abs(whole_pet_sample[slice_batch] - whole_GT_pet[slice_batch]) L1_loss = _L1_loss.mean() pet_sample_file_name = str(syn_folder / f'{_mri_uid}_{img_label}_syn_pet.nii.gz') pet_sample_img = nib.Nifti1Image(whole_pet_sample[slice_batch].squeeze(), affine=affine) pet_sample_img.to_filename(pet_sample_file_name) print(f'MRI -> PET: {_mri_uid}_{img_label}: {L1_loss:.6f}') with open(str(syn_folder / f'all_eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'MRI -> PET: {_mri_uid}_{img_label}: {L1_loss:.6f}') if get_ROI_loss: ROI_loss = _L1_loss * self.ROI_mask ROI_loss = ROI_loss.mean() print(f'MRI -> PET ROI loss: {_mri_uid}_{img_label}: {ROI_loss:.6f}') with open(str(syn_folder / f'all_eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'MRI -> PET ROI loss: {_mri_uid}_{img_label}: {ROI_loss:.6f}') roi_losses.append(ROI_loss) else: whole_pet_sample_img = nib.Nifti1Image(whole_pet_sample[slice_batch].squeeze(), affine=affine) whole_pet_sample_img.to_filename(str(self.evaluate_folder / f'whole_sample_pet_{_mri_uid}_{slice_batch}_{img_label}.nii.gz')) whole_GT_pet_img = nib.Nifti1Image(whole_GT_pet[slice_batch].squeeze(), affine=affine) whole_GT_pet_img.to_filename(str(self.evaluate_folder / f'whole_GT_pet_{_mri_uid}_{slice_batch}_{img_label}.nii.gz')) error_map_img = nib.Nifti1Image((whole_pet_sample[slice_batch] - whole_GT_pet[slice_batch]).squeeze(), affine=affine) error_map_img.to_filename(str(self.evaluate_folder / f'error_map_{_mri_uid}_{slice_batch}_{img_label}.nii.gz')) _L1_loss = np.abs(whole_pet_sample[slice_batch] - whole_GT_pet[slice_batch]) L1_loss = _L1_loss.mean() print(f'MRI -> PET: {_mri_uid}_{img_label}: {L1_loss:.6f}') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'MRI -> PET: {_mri_uid}_{img_label}: {L1_loss:.6f}') if get_ROI_loss: ROI_loss = _L1_loss * self.ROI_mask ROI_loss = ROI_loss.mean() print(f'MRI -> PET ROI loss: {_mri_uid}_{img_label}: {ROI_loss:.6f}') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'MRI -> PET ROI loss: {_mri_uid}_{img_label}: {ROI_loss:.6f}') roi_losses.append(ROI_loss) if self.model_cycling and not synthesis: L1_loss_mri = np.abs(whole_mri_sample[slice_batch] - whole_GT_mri[slice_batch]).mean() print(f'PET -> MRI: {_mri_uid}_{img_label}: {L1_loss_mri:.6f}') print('====================') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'PET -> MRI: {_mri_uid}_{img_label}: {L1_loss_mri:.6f}') f.write('\n') f.write('====================') if not synthesis: if flag == 0: break flag += 1 sample_images_list = torch.cat(sample_images_list, dim = 0).to(self.device) real_images_list = torch.cat(real_images_list, dim = 0).to(self.device) averaged_sample_images_list = torch.cat(averaged_sample_images_list, dim = 0).to(self.device) if not synthesis: try: import matplotlib.pyplot as plt e_map = error_map_list for num in range(len(e_map)): for slice_batch in range(e_map[num].shape[0]): save_dir = os.path.join(self.evaluate_folder, f'error_map_{slice_batch}') if not os.path.exists(save_dir): os.makedirs(save_dir) save_path = os.path.join(save_dir, f'slice_{num}.png') plt.imshow(e_map[num][slice_batch].squeeze().detach().cpu().numpy(), cmap='seismic', vmin=-1, vmax=1) # plt.colorbar() LABEL_MAP = {0: 'CN', 1: 'AD', 2: 'MCI'} plt.text(0, 0, str(LABEL_MAP[int(error_map_label[slice_batch].detach().cpu().numpy())]), color='red', fontsize=15, va='top') plt.savefig(save_path) plt.close() except ImportError: print('matplotlib not installed, skip saving error heatmap') error_map_list = torch.stack(error_map_list, dim = 0).to(self.device) print(error_map_list.shape) for batch in range(error_map_list.shape[1]): utils.save_image(error_map_list[:, batch, ...], os.path.join(self.evaluate_folder, 'error_map.png'), nrow = int(math.sqrt(self.num_samples))) if not synthesis: recon_loss_l2 = F.mse_loss(sample_images_list, real_images_list) print(f'test recon L2 loss: {recon_loss_l2:.4f}') recon_loss_l1 = F.l1_loss(sample_images_list, real_images_list) print(f'test recon L1 loss: {recon_loss_l1:.4f}') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'test recon L2 loss: {recon_loss_l2:.4f}') f.write('\n') f.write(f'test recon L1 loss: {recon_loss_l1:.4f}') psnr_score = self.psnr(real_images_list, sample_images_list).mean().detach().cpu().numpy() print(f'psnr_score: {str(psnr_score)}') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'psnr_score: {str(psnr_score)}') ssim_score = ssim(real_images_list, sample_images_list).detach().cpu().numpy() print(f'ssim_score: {str(ssim_score)}') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'ssim_score: {str(ssim_score)}') f.write('\n') ### evaluate the averaged sample images recon_loss_l2 = F.mse_loss(averaged_sample_images_list, real_images_list) print(f'test recon L2 loss (averaged sample): {recon_loss_l2:.4f}') recon_loss_l1 = F.l1_loss(averaged_sample_images_list, real_images_list) print(f'test recon L1 loss (averaged sample): {recon_loss_l1:.4f}') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'test recon L2 loss (averaged sample): {recon_loss_l2:.4f}') f.write('\n') f.write(f'test recon L1 loss (averaged sample): {recon_loss_l1:.4f}') if get_ROI_loss: roi_losses = sum(roi_losses) / len(roi_losses) print(f'test ROI loss: {roi_losses: .4f}') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'test ROI loss: {roi_losses: .6f}') f.write('\n') psnr_score = self.psnr(real_images_list, averaged_sample_images_list).mean().detach().cpu().numpy() print(f'psnr_score (averaged sample): {str(psnr_score)}') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'psnr_score (averaged sample): {str(psnr_score)}') ssim_score = ssim(real_images_list, averaged_sample_images_list).detach().cpu().numpy() print(f'ssim_score (averaged sample): {str(ssim_score)}') with open(str(self.evaluate_folder / f'eval_scores.txt'), 'a') as f: f.write('\n') f.write(f'ssim_score (averaged sample): {str(ssim_score)}') f.write('\n')
40,801
Python
.py
647
40.846986
162
0.503288
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,716
data_utils.py
ai-med_PASTA/src/utils/data_utils.py
import numpy as np import torch import torchio as tio import torch.nn.functional as F import monai.transforms as montrans import math def roi_crop_3d(image): # 3d image as input # Mask of non-black pixels (assuming image has a single channel). mask = image > 0 # Coordinates of non-black pixels. coords = np.argwhere(mask) # Bounding box of non-black pixels. x0, y0, z0 = coords.min(axis=0) x1, y1, z1 = coords.max(axis=0) + 1 # slices are exclusive at the top # Get the contents of the bounding box. cropped = image[x0:x1, y0:y1, z0:z1] padded_crop = tio.CropOrPad( np.max(cropped.shape))(cropped.copy()[None]) # padded_crop = np.transpose(padded_crop, (1, 2, 3, 0)) return padded_crop def roi_crop(image): # Mask of non-black pixels (assuming image has a single channel). mask = image > 0 # Coordinates of non-black pixels. coords = np.argwhere(mask) # Bounding box of non-black pixels. x0, y0 = coords.min(axis=0) x1, y1 = coords.max(axis=0) + 1 # slices are exclusive at the top # Get the contents of the bounding box. cropped = image[x0:x1, y0:y1] cropped = cropped[np.newaxis, :, :, np.newaxis] padded_crop = tio.CropOrPad( (np.max(cropped.shape), np.max(cropped.shape), 1))(cropped.copy()) # padded_crop = tio.RescaleIntensity(out_min_max=(0, 1))(padded_crop) padded_crop = padded_crop.squeeze(-1) # padded_crop = np.transpose(padded_crop, (1, 2, 3, 0)) return padded_crop def crop_minimally_keep_ratio(image, target_size): original_height, original_width = image.shape[-2:] target_height, target_width = target_size # Calculate the aspect ratios aspect_ratio_original = original_width / original_height aspect_ratio_target = target_width / target_height # Determine whether to crop width or height if aspect_ratio_original > aspect_ratio_target: # Crop width new_width_cropped = original_height * aspect_ratio_target left_boundary = int((original_width - new_width_cropped) / 2) right_boundary = int(original_width - left_boundary) cropped_image = image[:, left_boundary:right_boundary] else: # Crop height new_height_cropped = original_width / aspect_ratio_target top_boundary = int((original_height - new_height_cropped) / 2) bottom_boundary = int(original_height - top_boundary) cropped_image = image[top_boundary:bottom_boundary, :] return cropped_image # data transforms def get_3d_image_transform(resolution, random_crop: bool = False, random_flip: bool = False, random_affine: bool = False): # Image sizes PET & MRI Dataset {113, 137, 113} img_transforms = [ tio.RescaleIntensity(out_min_max=(0, 1)) ] if resolution: CropOrPad = tio.CropOrPad(resolution) img_transforms.append(CropOrPad) # Rescale = montrans.Resize(resolution) # img_transforms.append(Rescale) if random_flip: Flip = tio.RandomFlip(axes = (0,1,2), flip_probability=0.5) img_transforms.append(Flip) if random_affine: randomAffineWithRot = tio.RandomAffine( scales=0.05, degrees=90, # +-90 degree in each dimension translation=8, # +-8 pixels offset in each dimension. image_interpolation="linear", default_pad_value="otsu", p=0.5, ) img_transforms.append(randomAffineWithRot) img_transform = montrans.Compose(img_transforms) return img_transform def rescale_intensity(img): img = img[np.newaxis, :, :, np.newaxis] img = tio.RescaleIntensity(out_min_max=(0, 1))(img) img = img.squeeze(0) img = img.squeeze(-1) return img def rescale_intensity_3D(img): img = img[np.newaxis, :, :, :] img = tio.RescaleIntensity(out_min_max=(0, 1))(img) img = img.squeeze(0) return img def CropOrPad_3D(img, resolution): img = img[np.newaxis, :, :, :] img = tio.CropOrPad(resolution)(img) img = img.squeeze(0) return img def resample_and_reshape(img, new_spacing=(1.5, 1.5, 1.5), target_shape=(113, 137, 113)): # resample to 1.5mm spacing using monai resampled_mri = tio.Resample(new_spacing, image_interpolation = 'linear')(img[np.newaxis]) rescaled_mri = tio.CropOrPad(target_shape)(resampled_mri) rescaled_mri = rescaled_mri.squeeze(0) return rescaled_mri def process_tabular_data(tabular_data): # handle the nan entries in the tabular data: append the missing indicator mask # at the end of the tabular data, except for the age, sex, edu which always exist tabular_data = tabular_data[:6] tabular_data = np.array(tabular_data).astype(np.float32) tabular_mask = np.isnan(tabular_data[3:]) tabular_mask = np.logical_not(tabular_mask) tabular_data = np.nan_to_num(tabular_data, copy=False) # concat the mask to the tabular data tabular_data = np.concatenate((tabular_data, tabular_mask), axis=0) tabular_data = torch.from_numpy(tabular_data) return tabular_data def data_minimal_process(resolution, input_scan, data_transform): if not np.any(input_scan): # return the image of same size with all zeros input_scan = np.zeros_like(input_scan) input_scan = np.array(input_scan).astype(np.float32) # if input_scan.shape[0] / input_scan.shape[1] != resolution[0] / resolution[1]: # input_scan = crop_minimally_keep_ratio(input_scan, resolution) input_scan = data_transform(input_scan) return input_scan def pad_slices(slices_list, num_slices_needed, at_beginning): """ Helper function to pad the given slices_list with zeros. """ # Create the zero slices zero_slices = [np.zeros_like(slices_list[0]) for _ in range(num_slices_needed)] # Add the zero slices to the given list if at_beginning: return zero_slices + slices_list else: return slices_list + zero_slices def get_neighboring_slices(output_dim, direction, slice_num, scan): scan_shape = scan.shape # Number of slices before and after the current slice half_dim = (output_dim - 1) // 2 # Handle edge cases: pad with zeros if necessary start_idx = max(0, slice_num - half_dim) if direction == 'coronal': end_idx = min(scan_shape[1], slice_num + half_dim + 1) neighboring_slices = [scan[:, idx, :] for idx in range(start_idx, end_idx)] padding_before = (output_dim - len(neighboring_slices)) if start_idx == 0 else 0 padding_after = (output_dim - len(neighboring_slices) - padding_before) if end_idx == scan_shape[1] else 0 elif direction == 'sagittal': end_idx = min(scan_shape[0], slice_num + half_dim + 1) neighboring_slices = [scan[idx, :, :] for idx in range(start_idx, end_idx)] padding_before = (output_dim - len(neighboring_slices)) if start_idx == 0 else 0 padding_after = (output_dim - len(neighboring_slices) - padding_before) if end_idx == scan_shape[0] else 0 elif direction == 'axial': end_idx = min(scan_shape[2], slice_num + half_dim + 1) neighboring_slices = [scan[:, :, idx] for idx in range(start_idx, end_idx)] padding_before = (output_dim - len(neighboring_slices)) if start_idx == 0 else 0 padding_after = (output_dim - len(neighboring_slices) - padding_before) if end_idx == scan_shape[2] else 0 if padding_before > 0: neighboring_slices = pad_slices(neighboring_slices, padding_before, at_beginning=True) if padding_after > 0: neighboring_slices = pad_slices(neighboring_slices, padding_after, at_beginning=False) # Stack the slices to form the image with output_dim channels _output_data = np.stack(neighboring_slices, axis=0) return _output_data def multislice_data_minimal_process(output_dim, resolution, input_scan, data_transform): processed_scan = np.zeros((output_dim, input_scan.shape[1], input_scan.shape[2])).astype(np.float32) for i in range(input_scan.shape[0]): _input_data = input_scan[i, :, :] _input_data = data_minimal_process(resolution, _input_data, data_transform) processed_scan[i, :, :] = _input_data return processed_scan def gaussian_weight(x, b, c): return math.exp(-((x - b) ** 2) / (2 * c ** 2)) def reconstruct_scan_from_2_5D_slices(sets_of_slices): """ Reconstruct a 3D scan from sets of slices. Parameters: - sets_of_slices: a List of tensor sets. Each tensor set has shape (B, C, H, W). Returns: - A reconstructed 3D tensor scan of shape (B, N, H, W). """ # Determine the number of slices in each set and validate it's odd B, slices_per_set, h, w = sets_of_slices[0].shape slice_shape = (h, w) if slices_per_set % 2 == 0: raise ValueError("Number of slices per set should be odd.") # Compute the offset due to extra slices on each side of the set offset = slices_per_set // 2 # Total number of slices in the final virtual 3D scan n = len(sets_of_slices) + 2 * offset # Initialize the 3D tensor and the counter tensor scan_3D = torch.zeros(B, n, *slice_shape).to(sets_of_slices[0].device) count = torch.zeros(B, n, *slice_shape).to(sets_of_slices[0].device) c = offset / 3.0 # You can adjust this for desired spread # weights = [gaussian_weight(i, offset, c) for i in range(slices_per_set)] # gaussian weights = [1 - abs(offset - i) / float(offset) for i in range(slices_per_set)] # linear weights_tensor = torch.tensor(weights).to(sets_of_slices[0].device) for i, set_of_slices in enumerate(sets_of_slices): for j in range(slices_per_set): # weight the slice by its position in the set idx = i + j scan_3D[:, idx] += set_of_slices[:, j] * weights_tensor[j] count[:, idx] += weights_tensor[j] # count[:, idx] += 1 # Get the average of overlapping slices scan_3D /= count.clamp(min=1) # clamp to prevent division by zero # Extract slices from offset to n-offset and append to a list result_slices = [scan_3D[:, i] for i in range(offset, n - offset)] return result_slices
10,341
Python
.py
209
42.818182
122
0.667502
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,717
utils.py
ai-med_PASTA/src/utils/utils.py
import math import torch import argparse import yaml import random import numpy as np # helpers functions def load_config_from_yaml(config_file_path): with open(config_file_path, 'r') as f: config_data = yaml.safe_load(f) args = argparse.Namespace(**config_data) return args def exists(x): return x is not None def default(val, d): if exists(val): return val return d() if callable(d) else d def identity(t, *args, **kwargs): return t def cycle(dl): while True: for data in dl: yield data def cycle_pair(dl): while True: for mri_data, pet_data in dl: yield mri_data, pet_data def has_int_squareroot(num): return (math.sqrt(num) ** 2) == num def num_to_groups(num, divisor): #(4,8) groups = num // divisor # 0 remainder = num % divisor # 4 arr = [divisor] * groups # [0] if remainder > 0: arr.append(remainder) # [0,4] return arr def convert_image_to_fn(img_type, image): if image.mode != img_type: return image.convert(img_type) return image # normalization functions def normalize_to_neg_one_to_one(img): return img * 2 - 1 def unnormalize_to_zero_to_one(t): return (t + 1) * 0.5 def str2bool(v): """ https://stackoverflow.com/questions/15008758/parsing-boolean-values-with-argparse """ if isinstance(v, bool): return v if v.lower() in ("yes", "true", "t", "y", "1"): return True elif v.lower() in ("no", "false", "f", "n", "0"): return False else: raise argparse.ArgumentTypeError("boolean value expected") def add_dict_to_argparser(parser, default_dict): for k, v in default_dict.items(): v_type = type(v) if v is None: v_type = str elif isinstance(v, bool): v_type = str2bool parser.add_argument(f"--{k}", default=v, type=v_type) def print_model_size(model): num_params = sum(p.numel() for p in model.parameters() if p.requires_grad) print(f"Number of parameters: {num_params}") param_size = 0 for param in model.parameters(): param_size += param.nelement() * param.element_size() buffer_size = 0 for buffer in model.buffers(): buffer_size += buffer.nelement() * buffer.element_size() size_all_mb = (param_size + buffer_size) / 1024**2 print('model size: {:.3f}MB'.format(size_all_mb)) def set_seed_everywhere(seed): """Set seed for reproducibility.""" # Python random.seed(seed) # Numpy np.random.seed(seed) # PyTorch torch.manual_seed(seed) if torch.cuda.is_available(): torch.cuda.manual_seed(seed) torch.cuda.manual_seed_all(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False def positional_encoding_2d(x, h, w): B = x.shape[0] # Generate row and column indices row_indices = torch.linspace(0, 1, h).view(1, -1, 1).expand(B, -1, -1).to(x.device) col_indices = torch.linspace(0, 1, w).view(1, 1, -1).expand(B, -1, -1).to(x.device) # Reshape x for broadcasting x = x.view(B, 1, 1) # Create sinusoidal patterns modulated by the input value batch row_pattern = torch.sin(2 * 3.14159 * x * 10 * row_indices) col_pattern = torch.sin(2 * 3.14159 * x * 10 * col_indices) # Combine row and column patterns encoded = row_pattern + col_pattern return encoded
3,458
Python
.py
103
28.048544
87
0.639132
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,718
respace.py
ai-med_PASTA/src/diffusion/respace.py
import numpy as np import torch as th from .gaussian_diffusion import GaussianDiffusion def space_timesteps(num_timesteps, section_counts): """ Create a list of timesteps to use from an original diffusion process, given the number of timesteps we want to take from equally-sized portions of the original process. For example, if there's 300 timesteps and the section counts are [10,15,20] then the first 100 timesteps are strided to be 10 timesteps, the second 100 are strided to be 15 timesteps, and the final 100 are strided to be 20. If the stride is a string starting with "ddim", then the fixed striding from the DDIM paper is used, and only one section is allowed. :param num_timesteps: the number of diffusion steps in the original process to divide up. :param section_counts: either a list of numbers, or a string containing comma-separated numbers, indicating the step count per section. As a special case, use "ddimN" where N is a number of steps to use the striding from the DDIM paper. :return: a set of diffusion steps from the original process to use. """ if isinstance(section_counts, str): if section_counts.startswith("ddim"): desired_count = int(section_counts[len("ddim") :]) for i in range(1, num_timesteps): if len(range(0, num_timesteps, i)) == desired_count: return set(range(0, num_timesteps, i)) raise ValueError( f"cannot create exactly {num_timesteps} steps with an integer stride" ) section_counts = [int(x) for x in section_counts.split(",")] size_per = num_timesteps // len(section_counts) extra = num_timesteps % len(section_counts) start_idx = 0 all_steps = [] for i, section_count in enumerate(section_counts): size = size_per + (1 if i < extra else 0) if size < section_count: raise ValueError( f"cannot divide section of {size} steps into {section_count}" ) if section_count <= 1: frac_stride = 1 else: frac_stride = (size - 1) / (section_count - 1) cur_idx = 0.0 taken_steps = [] for _ in range(section_count): taken_steps.append(start_idx + round(cur_idx)) cur_idx += frac_stride all_steps += taken_steps start_idx += size return set(all_steps) class SpacedDiffusion(GaussianDiffusion): """ A diffusion process which can skip steps in a base diffusion process. :param use_timesteps: a collection (sequence or set) of timesteps from the original diffusion process to retain. :param kwargs: the kwargs to create the base diffusion process. """ def __init__(self, use_timesteps, **kwargs): self.use_timesteps = set(use_timesteps) self.timestep_map = [] self.original_num_steps = kwargs["timesteps"] base_diffusion = GaussianDiffusion(**kwargs) # pylint: disable=missing-kwoa last_alpha_cumprod = 1.0 new_betas = [] for i, alpha_cumprod in enumerate(base_diffusion.alphas_cumprod): if i in self.use_timesteps: new_betas.append(1 - alpha_cumprod / last_alpha_cumprod) last_alpha_cumprod = alpha_cumprod self.timestep_map.append(i) kwargs["betas"] = np.array(new_betas) super().__init__(**kwargs) def p_mean_variance( self, model, *args, **kwargs ): # pylint: disable=signature-differs return super().p_mean_variance(self._wrap_model(model), *args, **kwargs) def training_losses( self, model, *args, **kwargs ): # pylint: disable=signature-differs return super().training_losses(self._wrap_model(model), *args, **kwargs) def condition_mean(self, cond_fn, *args, **kwargs): return super().condition_mean(self._wrap_model(cond_fn), *args, **kwargs) def condition_score(self, cond_fn, *args, **kwargs): return super().condition_score(self._wrap_model(cond_fn), *args, **kwargs) def _wrap_model(self, model): if isinstance(model, _WrappedModel): return model return _WrappedModel( model, self.timestep_map, self.rescale_timesteps, self.original_num_steps ) def _scale_timesteps(self, t): # Scaling is done by the wrapped model. return t class _WrappedModel: def __init__(self, model, timestep_map, rescale_timesteps, original_num_steps): self.model = model self.timestep_map = timestep_map self.rescale_timesteps = rescale_timesteps self.original_num_steps = original_num_steps def __call__(self, x, ts, **kwargs): map_tensor = th.tensor(self.timestep_map, device=ts.device, dtype=ts.dtype) new_ts = map_tensor[ts] if self.rescale_timesteps: new_ts = new_ts.float() * (1000.0 / self.original_num_steps) return self.model(x, new_ts, **kwargs)
5,192
Python
.py
108
38.555556
85
0.628752
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,719
gaussian_diffusion.py
ai-med_PASTA/src/diffusion/gaussian_diffusion.py
""" This code started out as a PyTorch port of Ho et al's diffusion models: https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py Docstrings have been added, as well as DDIM sampling and a new collection of beta schedules. """ import enum import numpy as np import torch import torch as th from torch.cuda.amp import autocast from src.model.nn import mean_flat from .losses import normal_kl, discretized_gaussian_log_likelihood from src.evals.ssim import * from typing import List from src.model.unet import UNetModel from src.diffusion.diff_utils import * class ModelMeanType(enum.Enum): """ Which type of output the model predicts. """ PREVIOUS_X = enum.auto() # the model predicts x_{t-1} START_X = enum.auto() # the model predicts x_0 EPSILON = enum.auto() # the model predicts epsilon (noise) VELOCITY = enum.auto() # the model predicts the velocity v class ModelVarType(enum.Enum): """ What is used as the model's output variance. The LEARNED_RANGE option has been added to allow the model to predict values between FIXED_SMALL and FIXED_LARGE, making its job easier. """ LEARNED = enum.auto() FIXED_SMALL = enum.auto() FIXED_LARGE = enum.auto() LEARNED_RANGE = enum.auto() class LossType(enum.Enum): MSE = enum.auto() # use raw MSE loss (and KL when learning variances) RESCALED_MSE = ( enum.auto() ) # use raw MSE loss (with RESCALED_KL when learning variances) KL = enum.auto() # use the variational lower-bound RESCALED_KL = enum.auto() # like KL, but rescale to estimate the full VLB MAE = enum.auto() # use raw MAE loss (and KL when learning variances) def is_vb(self): return self == LossType.KL or self == LossType.RESCALED_KL class GaussianDiffusion(th.nn.Module): """ Utilities for training and sampling diffusion models. Ported directly from here, and then adapted over time to further experimentation. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/diffusion_utils_2.py#L42 :param betas: a 1-D numpy array of betas for each diffusion timestep, starting at T and going to 1. :param model_mean_type: a ModelMeanType determining what the model outputs. :param model_var_type: a ModelVarType determining how variance is output. :param loss_type: a LossType determining the loss function to use. :param rescale_timesteps: if True, pass floating point timesteps into the model so that they are always scaled like in the original paper (0 to 1000). """ def __init__( self, model, encoder=None, *, betas = None, beta_schedule = 'linear', timesteps = 1000, model_mean_type = ModelMeanType.EPSILON, model_var_type = ModelVarType.LEARNED_RANGE, loss_type = LossType.MSE, rescale_timesteps=False, gen_type="ddim", use_fp16=False, condition=True, reconstructed_loss=None, recon_weight=None, rescale_intensity = True, ): super().__init__() self.model = model self.encoder = encoder self.model_mean_type = model_mean_type self.model_var_type = model_var_type self.loss_type = loss_type self.rescale_timesteps = rescale_timesteps self.gen_type = gen_type self.use_fp16 = use_fp16 self.condition = condition self.reconstructed_loss = reconstructed_loss self.recon_weight = recon_weight self.rescale_intensity = rescale_intensity self.image_size = model.image_size if betas is None: betas = get_named_beta_schedule(beta_schedule, timesteps) else: print("Calculated beta available") # Use float64 for accuracy. betas = np.array(betas, dtype=np.float64) self.betas = betas assert len(betas.shape) == 1, "betas must be 1-D" assert (betas > 0).all() and (betas <= 1).all() self.num_timesteps = int(betas.shape[0]) alphas = 1.0 - betas self.alphas_cumprod = np.cumprod(alphas, axis=0) self.alphas_cumprod_prev = np.append(1.0, self.alphas_cumprod[:-1]) self.alphas_cumprod_next = np.append(self.alphas_cumprod[1:], 0.0) assert self.alphas_cumprod_prev.shape == (self.num_timesteps,) # calculations for diffusion q(x_t | x_{t-1}) and others self.sqrt_alphas_cumprod = np.sqrt(self.alphas_cumprod) self.sqrt_one_minus_alphas_cumprod = np.sqrt(1.0 - self.alphas_cumprod) self.log_one_minus_alphas_cumprod = np.log(1.0 - self.alphas_cumprod) self.sqrt_recip_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod) self.sqrt_recipm1_alphas_cumprod = np.sqrt(1.0 / self.alphas_cumprod - 1) # calculations for posterior q(x_{t-1} | x_t, x_0) self.posterior_variance = ( betas * (1.0 - self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) ) # log calculation clipped because the posterior variance is 0 at the # beginning of the diffusion chain. self.posterior_log_variance_clipped = np.log( np.append(self.posterior_variance[1], self.posterior_variance[1:]) ) self.posterior_mean_coef1 = ( betas * np.sqrt(self.alphas_cumprod_prev) / (1.0 - self.alphas_cumprod) ) self.posterior_mean_coef2 = ( (1.0 - self.alphas_cumprod_prev) * np.sqrt(alphas) / (1.0 - self.alphas_cumprod) ) self.normalize = normalize_to_neg_one_to_one if rescale_intensity else identity self.unnormalize = unnormalize_to_zero_to_one if rescale_intensity else identity def q_mean_variance(self, x_start, t): """ Get the distribution q(x_t | x_0). :param x_start: the [N x C x ...] tensor of noiseless inputs. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :return: A tuple (mean, variance, log_variance), all of x_start's shape. """ mean = ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start ) variance = _extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape) log_variance = _extract_into_tensor( self.log_one_minus_alphas_cumprod, t, x_start.shape ) return mean, variance, log_variance def q_sample(self, x_start, t, noise=None): """ Diffuse the data for a given number of diffusion steps. In other words, sample from q(x_t | x_0). :param x_start: the initial data batch. :param t: the number of diffusion steps (minus 1). Here, 0 means one step. :param noise: if specified, the split-out normal noise. :return: A noisy version of x_start. """ if noise is None: noise = th.randn_like(x_start) assert noise.shape == x_start.shape return ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start + _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise ) def q_posterior_mean_variance(self, x_start, x_t, t): """ Compute the mean and variance of the diffusion posterior: q(x_{t-1} | x_t, x_0) """ assert x_start.shape == x_t.shape posterior_mean = ( _extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start + _extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t ) posterior_variance = _extract_into_tensor(self.posterior_variance, t, x_t.shape) posterior_log_variance_clipped = _extract_into_tensor( self.posterior_log_variance_clipped, t, x_t.shape ) assert ( posterior_mean.shape[0] == posterior_variance.shape[0] == posterior_log_variance_clipped.shape[0] == x_start.shape[0] ) return posterior_mean, posterior_variance, posterior_log_variance_clipped def p_mean_variance( self, model, x, t, cond = None, clip_denoised=True, denoised_fn=None, model_kwargs=None ): """ Apply the model to get p(x_{t-1} | x_t), as well as a prediction of the initial x, x_0. :param model: the model, which takes a signal and a batch of timesteps as input. :param x: the [N x C x ...] tensor at time t. :param t: a 1-D Tensor of timesteps. :param clip_denoised: if True, clip the denoised signal into [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. Applies before clip_denoised. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :return: a dict with the following keys: - 'mean': the model mean output. - 'variance': the model variance output. - 'log_variance': the log of 'variance'. - 'pred_xstart': the prediction for x_0. """ model = self.model if model_kwargs is None: model_kwargs = {} tab_cond = None else: cond = model_kwargs['cond'] if cond is None else cond tab_cond = model_kwargs['tab_cond'] B, C = x.shape[:2] assert t.shape == (B,) with autocast(self.use_fp16): model_output = model(x, self._scale_timesteps(t), cond = cond, tab_cond = tab_cond) #, **model_kwargs) if self.model_var_type in [ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE]: assert model_output.shape == (B, C * 2, *x.shape[2:]) model_output, model_var_values = th.split(model_output, C, dim=1) if self.model_var_type == ModelVarType.LEARNED: model_log_variance = model_var_values model_variance = th.exp(model_log_variance) else: min_log = _extract_into_tensor( self.posterior_log_variance_clipped, t, x.shape ) max_log = _extract_into_tensor(np.log(self.betas), t, x.shape) # The model_var_values is [-1, 1] for [min_var, max_var]. frac = (model_var_values + 1) / 2 model_log_variance = frac * max_log + (1 - frac) * min_log model_variance = th.exp(model_log_variance) else: model_variance, model_log_variance = { # for fixedlarge, we set the initial (log-)variance like so # to get a better decoder log likelihood. ModelVarType.FIXED_LARGE: ( np.append(self.posterior_variance[1], self.betas[1:]), np.log(np.append(self.posterior_variance[1], self.betas[1:])), ), ModelVarType.FIXED_SMALL: ( self.posterior_variance, self.posterior_log_variance_clipped, ), }[self.model_var_type] model_variance = _extract_into_tensor(model_variance, t, x.shape) model_log_variance = _extract_into_tensor(model_log_variance, t, x.shape) def process_xstart(x): if denoised_fn is not None: x = denoised_fn(x) if clip_denoised: return x.clamp(-1, 1) return x if self.model_mean_type == ModelMeanType.PREVIOUS_X: pred_xstart = process_xstart( self._predict_xstart_from_xprev(x_t=x, t=t, xprev=model_output) ) model_mean = model_output elif self.model_mean_type in [ModelMeanType.START_X, ModelMeanType.EPSILON]: if self.model_mean_type == ModelMeanType.START_X: pred_xstart = process_xstart(model_output) else: pred_xstart = process_xstart( self._predict_xstart_from_eps(x_t=x, t=t, eps=model_output) ) model_mean, _, _ = self.q_posterior_mean_variance( x_start=pred_xstart, x_t=x, t=t ) elif self.model_mean_type == ModelMeanType.VELOCITY: v = model_output pred_xstart = process_xstart(self.predict_start_from_v(x, t, v)) model_mean, _, _ = self.q_posterior_mean_variance( x_start=pred_xstart, x_t=x, t=t ) else: raise NotImplementedError(self.model_mean_type) assert ( model_mean.shape == model_log_variance.shape == pred_xstart.shape == x.shape ) return { "mean": model_mean, "variance": model_variance, "log_variance": model_log_variance, "pred_xstart": pred_xstart, } def _predict_xstart_from_eps(self, x_t, t, eps): assert x_t.shape == eps.shape return ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * eps ) def _predict_xstart_from_xprev(self, x_t, t, xprev): assert x_t.shape == xprev.shape return ( # (xprev - coef2*x_t) / coef1 _extract_into_tensor(1.0 / self.posterior_mean_coef1, t, x_t.shape) * xprev - _extract_into_tensor( self.posterior_mean_coef2 / self.posterior_mean_coef1, t, x_t.shape ) * x_t ) def _predict_eps_from_xstart(self, x_t, t, pred_xstart): return ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) def predict_v(self, x_start, t, noise): return ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * noise - _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * x_start ) def predict_start_from_v(self, x_t, t, v): return ( _extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t - _extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v ) def _scale_timesteps(self, t): if self.rescale_timesteps: return t.float() * (1000.0 / self.num_timesteps) return t def condition_mean(self, cond_fn, p_mean_var, x, t, model_kwargs=None): """ Compute the mean for the previous step, given a function cond_fn that computes the gradient of a conditional log probability with respect to x. In particular, cond_fn computes grad(log(p(y|x))), and we want to condition on y. This uses the conditioning strategy from Sohl-Dickstein et al. (2015). """ gradient = cond_fn(x, self._scale_timesteps(t), **model_kwargs) new_mean = ( p_mean_var["mean"].float() + p_mean_var["variance"] * gradient.float() ) return new_mean def condition_score(self, cond_fn, p_mean_var, x, t, model_kwargs=None): """ Compute what the p_mean_variance output would have been, should the model's score function be conditioned by cond_fn. See condition_mean() for details on cond_fn. Unlike condition_mean(), this instead uses the conditioning strategy from Song et al (2020). """ alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape) eps = self._predict_eps_from_xstart(x, t, p_mean_var["pred_xstart"]) eps = eps - (1 - alpha_bar).sqrt() * cond_fn( x, self._scale_timesteps(t), **model_kwargs ) out = p_mean_var.copy() out["pred_xstart"] = self._predict_xstart_from_eps(x, t, eps) out["mean"], _, _ = self.q_posterior_mean_variance( x_start=out["pred_xstart"], x_t=x, t=t ) return out def p_sample( self, model, x, t, cond = None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, ): """ Sample x_{t-1} from the model at the given timestep. :param model: the model to sample from. :param x: the current tensor at x_{t-1}. :param t: the value of t, starting at 0 for the first diffusion step. :param clip_denoised: if True, clip the x_start prediction to [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. :param cond_fn: if not None, this is a gradient function that acts similarly to the model. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :return: a dict containing the following keys: - 'sample': a random sample from the model. - 'pred_xstart': a prediction of x_0. """ out = self.p_mean_variance( model, x, t, cond = cond, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) noise = th.randn_like(x) nonzero_mask = ( (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) ) # no noise when t == 0 if cond_fn is not None: out["mean"] = self.condition_mean( cond_fn, out, x, t, model_kwargs=model_kwargs ) sample = out["mean"] + nonzero_mask * th.exp(0.5 * out["log_variance"]) * noise return {"sample": sample, "pred_xstart": out["pred_xstart"]} def p_sample_loop( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, ): """ Generate samples from the model. :param model: the model module. :param shape: the shape of the samples, (N, C, H, W). :param noise: if specified, the noise from the encoder to sample. Should be of the same shape as `shape`. :param clip_denoised: if True, clip x_start predictions to [-1, 1]. :param denoised_fn: if not None, a function which applies to the x_start prediction before it is used to sample. :param cond_fn: if not None, this is a gradient function that acts similarly to the model. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :param device: if specified, the device to create the samples on. If not specified, use a model parameter's device. :param progress: if True, show a tqdm progress bar. :return: a non-differentiable batch of samples. """ final = None for sample in self.p_sample_loop_progressive( model, shape, noise=noise, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, device=device, progress=progress, ): final = sample return final["sample"] def p_sample_loop_progressive( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, ): """ Generate samples from the model and yield intermediate samples from each timestep of diffusion. Arguments are the same as p_sample_loop(). Returns a generator over dicts, where each dict is the return value of p_sample(). """ if device is None: device = next(model.parameters()).device assert isinstance(shape, (tuple, list)) if noise is not None: img = noise else: img = th.randn(*shape, device=device) indices = list(range(self.num_timesteps))[::-1] if progress: # Lazy import so that we don't depend on tqdm. from tqdm.auto import tqdm indices = tqdm(indices) for i in indices: t = th.tensor([i] * shape[0], device=device) with th.no_grad(): out = self.p_sample( model, img, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, ) yield out img = out["sample"] def ddim_sample( self, model, x, t, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, eta=0.0, ): """ Sample x_{t-1} from the model using DDIM. Same usage as p_sample(). """ out = self.p_mean_variance( model, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) if cond_fn is not None: out = self.condition_score(cond_fn, out, x, t, model_kwargs=model_kwargs) # Usually our model outputs epsilon, but we re-derive it # in case we used x_start or x_prev prediction. eps = self._predict_eps_from_xstart(x, t, out["pred_xstart"]) alpha_bar = _extract_into_tensor(self.alphas_cumprod, t, x.shape) alpha_bar_prev = _extract_into_tensor(self.alphas_cumprod_prev, t, x.shape) sigma = ( eta * th.sqrt((1 - alpha_bar_prev) / (1 - alpha_bar)) * th.sqrt(1 - alpha_bar / alpha_bar_prev) ) # Equation 12. noise = th.randn_like(x) mean_pred = ( out["pred_xstart"] * th.sqrt(alpha_bar_prev) + th.sqrt(1 - alpha_bar_prev - sigma ** 2) * eps ) nonzero_mask = ( (t != 0).float().view(-1, *([1] * (len(x.shape) - 1))) ) # no noise when t == 0 sample = mean_pred + nonzero_mask * sigma * noise return {"sample": sample, "pred_xstart": out["pred_xstart"]} def ddim_reverse_sample( self, model, x, t, clip_denoised=True, denoised_fn=None, model_kwargs=None, eta=0.0, ): """ Sample x_{t+1} from the model using DDIM reverse ODE. """ assert eta == 0.0, "Reverse ODE only for deterministic path" out = self.p_mean_variance( model, x, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, model_kwargs=model_kwargs, ) # Usually our model outputs epsilon, but we re-derive it # in case we used x_start or x_prev prediction. eps = ( _extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x.shape) * x - out["pred_xstart"] ) / _extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x.shape) alpha_bar_next = _extract_into_tensor(self.alphas_cumprod_next, t, x.shape) # Equation 12. reversed mean_pred = ( out["pred_xstart"] * th.sqrt(alpha_bar_next) + th.sqrt(1 - alpha_bar_next) * eps ) return {"sample": mean_pred, "pred_xstart": out["pred_xstart"]} def ddim_sample_loop( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, eta=0.0, ): """ Generate samples from the model using DDIM. Same usage as p_sample_loop(). """ final = None for sample in self.ddim_sample_loop_progressive( model, shape, noise=noise, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, device=device, progress=progress, eta=eta, ): final = sample return final["sample"] def ddim_sample_loop_progressive( self, model, shape, noise=None, clip_denoised=True, denoised_fn=None, cond_fn=None, model_kwargs=None, device=None, progress=False, eta=0.0, ): """ Use DDIM to sample from the model and yield intermediate samples from each timestep of DDIM. Same usage as p_sample_loop_progressive(). """ if device is None: device = next(model.parameters()).device assert isinstance(shape, (tuple, list)) if noise is not None: img = noise else: img = th.randn(*shape, device=device) indices = list(range(self.num_timesteps))[::-1] if progress: # Lazy import so that we don't depend on tqdm. from tqdm.auto import tqdm indices = tqdm(indices) for i in indices: t = th.tensor([i] * shape[0], device=device) with th.no_grad(): out = self.ddim_sample( model, img, t, clip_denoised=clip_denoised, denoised_fn=denoised_fn, cond_fn=cond_fn, model_kwargs=model_kwargs, eta=eta, ) yield out img = out["sample"] def _vb_terms_bpd( self, model, x_start, x_t, t, cond = None, clip_denoised=True, model_kwargs=None ): """ Get a term for the variational lower-bound. The resulting units are bits (rather than nats, as one might expect). This allows for comparison to other papers. :return: a dict with the following keys: - 'output': a shape [N] tensor of NLLs or KLs. - 'pred_xstart': the x_0 predictions. """ true_mean, _, true_log_variance_clipped = self.q_posterior_mean_variance( x_start=x_start, x_t=x_t, t=t ) out = self.p_mean_variance( model, x_t, t, cond = cond, clip_denoised=clip_denoised, model_kwargs=model_kwargs ) kl = normal_kl( true_mean, true_log_variance_clipped, out["mean"], out["log_variance"] ) kl = mean_flat(kl) / np.log(2.0) decoder_nll = -discretized_gaussian_log_likelihood( x_start, means=out["mean"], log_scales=0.5 * out["log_variance"] ) assert decoder_nll.shape == x_start.shape decoder_nll = mean_flat(decoder_nll) / np.log(2.0) # At the first timestep return the decoder NLL, # otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t)) output = th.where((t == 0), decoder_nll, kl) return {"output": output, "pred_xstart": out["pred_xstart"]} def training_losses(self, model, encoder = None, x_start = None, t = None, cond = None, tab_cond = None, model_kwargs=None, noise=None, loss_weight_mask = None): """ Compute training losses for a single timestep. :param model: the model to evaluate loss on. :param x_start: the [N x C x ...] tensor of inputs. :param t: a batch of timestep indices. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :param noise: if specified, the specific Gaussian noise to try to remove. :return: a dict with the key "loss" containing a tensor of shape [N]. Some mean or variance settings may also have other keys. """ if self.condition: assert cond is not None, "Must provide cond if condition is True" input_cond = cond.clone() if encoder is None: # concatenate mri as another channel of input x_start = torch.cat([x_start, cond], dim = 1) if loss_weight_mask is not None: loss_weight_mask = torch.cat([loss_weight_mask, torch.ones_like(cond)], dim = 1) cond = None recon_cond = None if encoder is not None and cond is not None: with autocast(self.use_fp16): if isinstance(encoder, UNetModel): recon_cond, cond = encoder(x = cond, return_features=True, tab_cond = tab_cond) assert isinstance(cond, List) else: cond = encoder(x = cond) if model_kwargs is None: model_kwargs = {} model_kwargs['cond'] = cond model_kwargs['tab_cond'] = tab_cond if noise is None: noise = th.randn_like(x_start) x_t = self.q_sample(x_start, t, noise=noise) terms = {'x_t': x_t} if self.loss_type == LossType.KL or self.loss_type == LossType.RESCALED_KL: terms["loss"] = self._vb_terms_bpd( model=model, x_start=x_start, x_t=x_t, t=t, cond = cond, clip_denoised=False, model_kwargs=model_kwargs, )["output"] if self.loss_type == LossType.RESCALED_KL: terms["loss"] *= self.num_timesteps elif self.loss_type == LossType.MSE or self.loss_type == LossType.RESCALED_MSE or self.loss_type == LossType.MAE: with autocast(self.use_fp16): # x_t is static wrt. to the diffusion process model_output = model(x_t, self._scale_timesteps(t), cond = cond, tab_cond = tab_cond) #, **model_kwargs) terms['model_output'] = model_output if self.model_var_type in [ ModelVarType.LEARNED, ModelVarType.LEARNED_RANGE, ]: B, C = x_t.shape[:2] # print(model_output.shape) assert model_output.shape == (B, C * 2, *x_t.shape[2:]) model_output, model_var_values = th.split(model_output, C, dim=1) # Learn the variance using the variational bound, but don't let # it affect our mean prediction. frozen_out = th.cat([model_output.detach(), model_var_values], dim=1) terms["vb"] = self._vb_terms_bpd( model=lambda *args, r=frozen_out: r, x_start=x_start, x_t=x_t, t=t, cond = cond, clip_denoised=False, model_kwargs=model_kwargs, )["output"] if self.loss_type == LossType.RESCALED_MSE: # Divide by 1000 for equivalence with initial implementation. # Without a factor of 1/1000, the VB term hurts the MSE term. terms["vb"] *= self.num_timesteps / 1000.0 target = { ModelMeanType.PREVIOUS_X: self.q_posterior_mean_variance( x_start=x_start, x_t=x_t, t=t )[0], ModelMeanType.START_X: x_start, ModelMeanType.EPSILON: noise, ModelMeanType.VELOCITY: self.predict_v(x_start, t, noise), }[self.model_mean_type] assert model_output.shape == target.shape == x_start.shape if loss_weight_mask is None: loss_weight_mask = torch.ones_like(target) if self.loss_type == LossType.MSE: terms["mse"] = mean_flat((target - model_output) ** 2 * loss_weight_mask) if "vb" in terms: terms["loss"] = terms["mse"] + terms["vb"] else: terms["loss"] = terms["mse"] elif self.loss_type == LossType.MAE: terms["mae"] = mean_flat(abs(target - model_output) * loss_weight_mask) if "vb" in terms: terms["loss"] = terms["mae"] + terms["vb"] else: terms["loss"] = terms["mae"] else: raise NotImplementedError(self.loss_type) if recon_cond is not None: # MRI -> PET as the predefined task in the conditioner arm input_cond = x_start if self.condition else None if self.reconstructed_loss == 'l2': terms['recon_loss'] = mean_flat((input_cond - recon_cond) ** 2 * loss_weight_mask) elif self.reconstructed_loss == 'l1': terms['recon_loss'] = mean_flat(abs(input_cond - recon_cond) * loss_weight_mask) elif self.reconstructed_loss is not None: raise NotImplementedError(self.reconstructed_loss) if self.recon_weight is not None: terms['loss'] += self.recon_weight * terms['recon_loss'] else: terms['loss'] += terms['recon_loss'] if self.model_mean_type == ModelMeanType.START_X: terms['ssim_loss'] = torch.mean(torch.stack([(1-ssim(target[:,i,...].unsqueeze(1), model_output[:,i,...].unsqueeze(1))) for i in range(target.shape[1])], dim = 0)) terms['loss'] += terms['ssim_loss'] return terms def _prior_bpd(self, x_start): """ Get the prior KL term for the variational lower-bound, measured in bits-per-dim. This term can't be optimized, as it only depends on the encoder. :param x_start: the [N x C x ...] tensor of inputs. :return: a batch of [N] KL values (in bits), one per batch element. """ batch_size = x_start.shape[0] t = th.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device) qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t) kl_prior = normal_kl( mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0 ) return mean_flat(kl_prior) / np.log(2.0) def calc_bpd_loop(self, model, x_start, clip_denoised=True, model_kwargs=None): """ Compute the entire variational lower-bound, measured in bits-per-dim, as well as other related quantities. :param model: the model to evaluate loss on. :param x_start: the [N x C x ...] tensor of inputs. :param clip_denoised: if True, clip denoised samples. :param model_kwargs: if not None, a dict of extra keyword arguments to pass to the model. This can be used for conditioning. :return: a dict containing the following keys: - total_bpd: the total variational lower-bound, per batch element. - prior_bpd: the prior term in the lower-bound. - vb: an [N x T] tensor of terms in the lower-bound. - xstart_mse: an [N x T] tensor of x_0 MSEs for each timestep. - mse: an [N x T] tensor of epsilon MSEs for each timestep. """ device = x_start.device batch_size = x_start.shape[0] vb = [] xstart_mse = [] mse = [] for t in list(range(self.num_timesteps))[::-1]: t_batch = th.tensor([t] * batch_size, device=device) noise = th.randn_like(x_start) x_t = self.q_sample(x_start=x_start, t=t_batch, noise=noise) # Calculate VLB term at the current timestep with th.no_grad(): out = self._vb_terms_bpd( model, x_start=x_start, x_t=x_t, t=t_batch, clip_denoised=clip_denoised, model_kwargs=model_kwargs, ) vb.append(out["output"]) xstart_mse.append(mean_flat((out["pred_xstart"] - x_start) ** 2)) eps = self._predict_eps_from_xstart(x_t, t_batch, out["pred_xstart"]) mse.append(mean_flat((eps - noise) ** 2)) vb = th.stack(vb, dim=1) xstart_mse = th.stack(xstart_mse, dim=1) mse = th.stack(mse, dim=1) prior_bpd = self._prior_bpd(x_start) total_bpd = vb.sum(dim=1) + prior_bpd return { "total_bpd": total_bpd, "prior_bpd": prior_bpd, "vb": vb, "xstart_mse": xstart_mse, "mse": mse, } def forward(self, img, cond = None, tab_cond = None, model_cycle = False, loss_weight_mask = None, *args, **kwargs): b, *_, device, img_size, = *img.shape, img.device, self.image_size t = torch.randint(0, self.num_timesteps, (b,), device=device).long() # random timesteps for each image in batch img = self.normalize(img) # normalize input to [-1, 1] cond = self.normalize(cond) # normalize input to [-1, 1] with autocast(self.use_fp16): if model_cycle: return self.training_losses(model = self.encoder, encoder = self.model, x_start = img, t = t, cond = cond, tab_cond = tab_cond, loss_weight_mask = loss_weight_mask, *args, **kwargs) else: return self.training_losses(model = self.model, encoder = self.encoder, x_start = img, t = t, cond = cond, tab_cond = tab_cond, loss_weight_mask = loss_weight_mask, *args, **kwargs) def sample(self, model=None, shape=None, noise=None, cond=None, tab_cond = None, x_start=None, clip_denoised=True, model_kwargs=None, progress=True): """ Args: x_start: given for the autoencoder """ cond = self.normalize(cond) if cond is not None else None if model is None: model = self.model if model_kwargs is None: model_kwargs = {} if self.condition: if self.encoder is not None: if isinstance(self.encoder, UNetModel): recon_cond, cond = self.encoder(cond, return_features=True, tab_cond = tab_cond) else: cond = self.encoder(cond) elif self.encoder is None: noise = torch.randn(*shape, device=cond.device) noise = torch.cat([noise, cond], dim = 1) cond = None recon_cond = None model_kwargs['x_start'] = x_start model_kwargs['cond'] = cond model_kwargs['tab_cond'] = tab_cond sample_fn = (self.ddim_sample_loop if self.gen_type == 'ddim' else self.p_sample_loop) sample = sample_fn(model, shape=shape, noise=noise, clip_denoised=clip_denoised, model_kwargs=model_kwargs, progress=progress) sample = self.unnormalize(sample).clamp(0, 1) if self.encoder is None: sample = sample[:, :sample.shape[1]//2, ...] return sample def _extract_into_tensor(arr, timesteps, broadcast_shape): """ Extract values from a 1-D numpy array for a batch of indices. :param arr: the 1-D numpy array. :param timesteps: a tensor of indices into the array to extract. :param broadcast_shape: a larger shape of K dimensions with the batch dimension equal to the length of timesteps. :return: a tensor of shape [batch_size, 1, ...] where the shape has K dims. """ res = th.from_numpy(arr).to(device=timesteps.device)[timesteps].float() while len(res.shape) < len(broadcast_shape): res = res[..., None] return res.expand(broadcast_shape)
41,060
Python
.py
933
32.28403
175
0.562652
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,720
losses.py
ai-med_PASTA/src/diffusion/losses.py
""" Helpers for various likelihood-based losses. These are ported from the original Ho et al. diffusion models codebase: https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/utils.py """ import numpy as np import torch as th def normal_kl(mean1, logvar1, mean2, logvar2): """ Compute the KL divergence between two gaussians. Shapes are automatically broadcasted, so batches can be compared to scalars, among other use cases. """ tensor = None for obj in (mean1, logvar1, mean2, logvar2): if isinstance(obj, th.Tensor): tensor = obj break assert tensor is not None, "at least one argument must be a Tensor" # Force variances to be Tensors. Broadcasting helps convert scalars to # Tensors, but it does not work for th.exp(). logvar1, logvar2 = [ x if isinstance(x, th.Tensor) else th.tensor(x).to(tensor) for x in (logvar1, logvar2) ] return 0.5 * ( -1.0 + logvar2 - logvar1 + th.exp(logvar1 - logvar2) + ((mean1 - mean2) ** 2) * th.exp(-logvar2) ) def approx_standard_normal_cdf(x): """ A fast approximation of the cumulative distribution function of the standard normal. """ return 0.5 * (1.0 + th.tanh(np.sqrt(2.0 / np.pi) * (x + 0.044715 * th.pow(x, 3)))) def discretized_gaussian_log_likelihood(x, *, means, log_scales): """ Compute the log-likelihood of a Gaussian distribution discretizing to a given image. :param x: the target images. It is assumed that this was uint8 values, rescaled to the range [-1, 1]. :param means: the Gaussian mean Tensor. :param log_scales: the Gaussian log stddev Tensor. :return: a tensor like x of log probabilities (in nats). """ assert x.shape == means.shape == log_scales.shape centered_x = x - means inv_stdv = th.exp(-log_scales) plus_in = inv_stdv * (centered_x + 1.0 / 255.0) cdf_plus = approx_standard_normal_cdf(plus_in) min_in = inv_stdv * (centered_x - 1.0 / 255.0) cdf_min = approx_standard_normal_cdf(min_in) log_cdf_plus = th.log(cdf_plus.clamp(min=1e-12)) log_one_minus_cdf_min = th.log((1.0 - cdf_min).clamp(min=1e-12)) cdf_delta = cdf_plus - cdf_min log_probs = th.where( x < -0.999, log_cdf_plus, th.where(x > 0.999, log_one_minus_cdf_min, th.log(cdf_delta.clamp(min=1e-12))), ) assert log_probs.shape == x.shape return log_probs
2,534
Python
.py
65
33.338462
109
0.655678
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,721
diff_utils.py
ai-med_PASTA/src/diffusion/diff_utils.py
import numpy as np import math import torch as th def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999): """ Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of (1-beta) over time from t = [0,1]. :param num_diffusion_timesteps: the number of betas to produce. :param alpha_bar: a lambda that takes an argument t from 0 to 1 and produces the cumulative product of (1-beta) up to that part of the diffusion process. :param max_beta: the maximum beta to use; use values lower than 1 to prevent singularities. """ betas = [] for i in range(num_diffusion_timesteps): t1 = i / num_diffusion_timesteps t2 = (i + 1) / num_diffusion_timesteps betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta)) return np.array(betas) def get_named_beta_schedule(schedule_name, num_diffusion_timesteps): """ Get a pre-defined beta schedule for the given name. The beta schedule library consists of beta schedules which remain similar in the limit of num_diffusion_timesteps. Beta schedules may be added, but should not be removed or changed once they are committed to maintain backwards compatibility. """ if schedule_name == "linear": # Linear schedule from Ho et al, extended to work for any number of # diffusion steps. scale = 1000 / num_diffusion_timesteps beta_start = scale * 0.0001 beta_end = scale * 0.02 return np.linspace( beta_start, beta_end, num_diffusion_timesteps, dtype=np.float64 ) elif schedule_name == "cosine": return betas_for_alpha_bar( num_diffusion_timesteps, lambda t: math.cos((t + 0.008) / 1.008 * math.pi / 2) ** 2, ) elif schedule_name == "sigmoid": start = -3 end = 3 tau = 1 clamp_min = 1e-5 steps = num_diffusion_timesteps + 1 t = torch.linspace(0, num_diffusion_timesteps, steps, dtype = torch.float64) / num_diffusion_timesteps v_start = torch.tensor(start / tau).sigmoid() v_end = torch.tensor(end / tau).sigmoid() alphas_cumprod = (-((t * (end - start) + start) / tau).sigmoid() + v_end) / (v_end - v_start) alphas_cumprod = alphas_cumprod / alphas_cumprod[0] betas = 1 - (alphas_cumprod[1:] / alphas_cumprod[:-1]) return torch.clip(betas, 0, 0.999) else: raise NotImplementedError(f"unknown beta schedule: {schedule_name}") def normalize_to_neg_one_to_one(img): return img * 2 - 1 def unnormalize_to_zero_to_one(t): return (t + 1) * 0.5 def identity(t, *args, **kwargs): return t
2,789
Python
.py
63
36.857143
110
0.639573
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,722
fp16_util.py
ai-med_PASTA/src/model/fp16_util.py
""" Helpers to train with 16-bit precision. """ import numpy as np import torch as th import torch.nn as nn from torch._utils import _flatten_dense_tensors, _unflatten_dense_tensors from . import logger INITIAL_LOG_LOSS_SCALE = 20.0 def convert_module_to_f16(l): """ Convert primitive modules to float16. """ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.half() if l.bias is not None: l.bias.data = l.bias.data.half() def convert_module_to_f32(l): """ Convert primitive modules to float32, undoing convert_module_to_f16(). """ if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)): l.weight.data = l.weight.data.float() if l.bias is not None: l.bias.data = l.bias.data.float() def make_master_params(param_groups_and_shapes): """ Copy model parameters into a (differently-shaped) list of full-precision parameters. """ master_params = [] for param_group, shape in param_groups_and_shapes: master_param = nn.Parameter( _flatten_dense_tensors( [param.detach().float() for (_, param) in param_group] ).view(shape) ) master_param.requires_grad = True master_params.append(master_param) return master_params def model_grads_to_master_grads(param_groups_and_shapes, master_params): """ Copy the gradients from the model parameters into the master parameters from make_master_params(). """ for master_param, (param_group, shape) in zip( master_params, param_groups_and_shapes ): master_param.grad = _flatten_dense_tensors( [param_grad_or_zeros(param) for (_, param) in param_group] ).view(shape) def master_params_to_model_params(param_groups_and_shapes, master_params): """ Copy the master parameter data back into the model parameters. """ # Without copying to a list, if a generator is passed, this will # silently not copy any parameters. for master_param, (param_group, _) in zip(master_params, param_groups_and_shapes): for (_, param), unflat_master_param in zip( param_group, unflatten_master_params(param_group, master_param.view(-1)) ): param.detach().copy_(unflat_master_param) def unflatten_master_params(param_group, master_param): return _unflatten_dense_tensors(master_param, [param for (_, param) in param_group]) def get_param_groups_and_shapes(named_model_params): named_model_params = list(named_model_params) scalar_vector_named_params = ( [(n, p) for (n, p) in named_model_params if p.ndim <= 1], (-1), ) matrix_named_params = ( [(n, p) for (n, p) in named_model_params if p.ndim > 1], (1, -1), ) return [scalar_vector_named_params, matrix_named_params] def master_params_to_state_dict( model, param_groups_and_shapes, master_params, use_fp16 ): if use_fp16: state_dict = model.state_dict() for master_param, (param_group, _) in zip( master_params, param_groups_and_shapes ): for (name, _), unflat_master_param in zip( param_group, unflatten_master_params(param_group, master_param.view(-1)) ): assert name in state_dict state_dict[name] = unflat_master_param else: state_dict = model.state_dict() for i, (name, _value) in enumerate(model.named_parameters()): assert name in state_dict state_dict[name] = master_params[i] return state_dict def state_dict_to_master_params(model, state_dict, use_fp16): if use_fp16: named_model_params = [ (name, state_dict[name]) for name, _ in model.named_parameters() ] param_groups_and_shapes = get_param_groups_and_shapes(named_model_params) master_params = make_master_params(param_groups_and_shapes) else: master_params = [state_dict[name] for name, _ in model.named_parameters()] return master_params def zero_master_grads(master_params): for param in master_params: param.grad = None def zero_grad(model_params): for param in model_params: # Taken from https://pytorch.org/docs/stable/_modules/torch/optim/optimizer.html#Optimizer.add_param_group if param.grad is not None: param.grad.detach_() param.grad.zero_() def param_grad_or_zeros(param): if param.grad is not None: return param.grad.data.detach() else: return th.zeros_like(param) class MixedPrecisionTrainer: def __init__( self, *, model, use_fp16=False, fp16_scale_growth=1e-3, initial_lg_loss_scale=INITIAL_LOG_LOSS_SCALE, ): self.model = model self.use_fp16 = use_fp16 self.fp16_scale_growth = fp16_scale_growth self.model_params = list(self.model.parameters()) self.master_params = self.model_params self.param_groups_and_shapes = None self.lg_loss_scale = initial_lg_loss_scale if self.use_fp16: self.param_groups_and_shapes = get_param_groups_and_shapes( self.model.named_parameters() ) self.master_params = make_master_params(self.param_groups_and_shapes) self.model.convert_to_fp16() def zero_grad(self): zero_grad(self.model_params) def backward(self, loss: th.Tensor): if self.use_fp16: loss_scale = 2 ** self.lg_loss_scale (loss * loss_scale).backward() else: loss.backward() def optimize(self, opt: th.optim.Optimizer): if self.use_fp16: return self._optimize_fp16(opt) else: return self._optimize_normal(opt) def _optimize_fp16(self, opt: th.optim.Optimizer): logger.logkv_mean("lg_loss_scale", self.lg_loss_scale) model_grads_to_master_grads(self.param_groups_and_shapes, self.master_params) grad_norm, param_norm = self._compute_norms(grad_scale=2 ** self.lg_loss_scale) if check_overflow(grad_norm): self.lg_loss_scale -= 1 logger.log(f"Found NaN, decreased lg_loss_scale to {self.lg_loss_scale}") zero_master_grads(self.master_params) return False logger.logkv_mean("grad_norm", grad_norm) logger.logkv_mean("param_norm", param_norm) for p in self.master_params: p.grad.mul_(1.0 / (2 ** self.lg_loss_scale)) opt.step() zero_master_grads(self.master_params) master_params_to_model_params(self.param_groups_and_shapes, self.master_params) self.lg_loss_scale += self.fp16_scale_growth return True def _optimize_normal(self, opt: th.optim.Optimizer): grad_norm, param_norm = self._compute_norms() logger.logkv_mean("grad_norm", grad_norm) logger.logkv_mean("param_norm", param_norm) opt.step() return True def _compute_norms(self, grad_scale=1.0): grad_norm = 0.0 param_norm = 0.0 for p in self.master_params: with th.no_grad(): param_norm += th.norm(p, p=2, dtype=th.float32).item() ** 2 if p.grad is not None: grad_norm += th.norm(p.grad, p=2, dtype=th.float32).item() ** 2 return np.sqrt(grad_norm) / grad_scale, np.sqrt(param_norm) def master_params_to_state_dict(self, master_params): return master_params_to_state_dict( self.model, self.param_groups_and_shapes, master_params, self.use_fp16 ) def state_dict_to_master_params(self, state_dict): return state_dict_to_master_params(self.model, state_dict, self.use_fp16) def check_overflow(value): return (value == float("inf")) or (value == -float("inf")) or (value != value)
7,962
Python
.py
194
32.974227
114
0.631327
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,723
unet.py
ai-med_PASTA/src/model/unet.py
from abc import abstractmethod import math import numpy as np import torch as th import torch.nn as nn import torch.nn.functional as F from numbers import Number from typing import NamedTuple, Tuple, Union, List from .fp16_util import convert_module_to_f16, convert_module_to_f32 from .nn import ( checkpoint, conv_nd, linear, avg_pool_nd, zero_module, normalization, timestep_embedding, ) device = th.device("cuda" if th.cuda.is_available() else "cpu") class AttentionPool2d(nn.Module): """ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py """ def __init__( self, spacial_dim: int, embed_dim: int, num_heads_channels: int, output_dim: int = None, ): super().__init__() self.positional_embedding = nn.Parameter( th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5 ) self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1) self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1) self.num_heads = embed_dim // num_heads_channels self.attention = QKVAttention(self.num_heads) def forward(self, x): b, c, *_spatial = x.shape x = x.reshape(b, c, -1) # NC(HW) x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1) x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1) x = self.qkv_proj(x) x = self.attention(x) x = self.c_proj(x) return x[:, :, 0] class TimestepBlock(nn.Module): """ Any module where forward() takes timestep embeddings as a second argument. """ @abstractmethod def forward(self, x, emb, cond = None, tab_cond = None): """ Apply the module to `x` given `emb` timestep embeddings. """ class TimestepEmbedSequential(nn.Sequential, TimestepBlock): """ A sequential module that passes timestep embeddings to the children that support it as an extra input. """ def forward(self, x, emb, cond = None, tab_cond = None): for layer in self: if isinstance(layer, TimestepBlock): x = layer(x, emb = emb, cond = cond, tab_cond = tab_cond) else: x = layer(x) return x class Upsample(nn.Module): """ An upsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then upsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims if use_conv: self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=1) # self.conv = nn.ConvTranspose2d(self.channels, self.out_channels, kernel_size=3, stride=2, padding=1, output_padding=1) def forward(self, x): assert x.shape[1] == self.channels, (x.shape[1], self.channels) if self.dims == 3: x = F.interpolate( x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest" ) else: x = F.interpolate(x, scale_factor=2, mode="nearest") if self.use_conv: x = self.conv(x) return x class Downsample(nn.Module): """ A downsampling layer with an optional convolution. :param channels: channels in the inputs and outputs. :param use_conv: a bool determining if a convolution is applied. :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then downsampling occurs in the inner-two dimensions. """ def __init__(self, channels, use_conv, dims=2, out_channels=None): super().__init__() self.channels = channels self.out_channels = out_channels or channels self.use_conv = use_conv self.dims = dims stride = 2 if dims != 3 else (1, 2, 2) if use_conv: self.op = conv_nd( dims, self.channels, self.out_channels, 3, stride=stride, padding=1 ) else: assert self.channels == self.out_channels self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride) def forward(self, x): assert x.shape[1] == self.channels return self.op(x) class ResBlock(TimestepBlock): """ A residual block that can optionally change the number of channels. :param channels: the number of input channels. :param emb_channels: the number of timestep embedding channels. :param dropout: the rate of dropout. :param out_channels: if specified, the number of out channels. :param use_conv: if True and out_channels is specified, use a spatial convolution instead of a smaller 1x1 convolution to change the channels in the skip connection. :param dims: determines if the signal is 1D, 2D, or 3D. :param use_checkpoint: if True, use gradient checkpointing on this module. :param up: if True, use this block for upsampling. :param down: if True, use this block for downsampling. """ def __init__( self, channels, emb_channels, dropout, out_channels=None, condition_dim = None, cond_emb_channels = 512, tab_cond_dim = 9, use_conv=False, use_scale_shift_norm=True, dims=2, use_checkpoint=False, up=False, down=False, use_time_condition = True, cond_apply_method = 'multi', ): super().__init__() self.channels = channels self.emb_channels = emb_channels self.dropout = dropout self.out_channels = out_channels or channels self.condition_dim = condition_dim self.cond_emb_channels = cond_emb_channels self.use_conv = use_conv self.use_checkpoint = use_checkpoint self.use_scale_shift_norm = use_scale_shift_norm self.use_time_condition = use_time_condition self.cond_apply_method = cond_apply_method self.in_layers = nn.Sequential( normalization(channels), nn.SiLU(), conv_nd(dims, channels, self.out_channels, 3, padding=1), ) self.updown = up or down if up: self.h_upd = Upsample(channels, True, dims) self.x_upd = Upsample(channels, True, dims) elif down: self.h_upd = Downsample(channels, True, dims) self.x_upd = Downsample(channels, True, dims) else: self.h_upd = self.x_upd = nn.Identity() if use_time_condition: self.emb_layers = nn.Sequential( nn.SiLU(), linear( emb_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels, ), ) if self.condition_dim is not None: # self.cond_emb_layers = nn.Sequential( # nn.SiLU(), # linear(self.cond_emb_channels, self.out_channels), # ) if True: self.tab_embed = nn.Sequential( linear(tab_cond_dim, self.condition_dim), nn.SiLU(), linear( self.condition_dim, self.out_channels, ), ) else: self.tab_embed = nn.Sequential( linear(tab_cond_dim, self.out_channels), ### AdaGN nn.SiLU(), linear( self.out_channels, 2 * self.out_channels if use_scale_shift_norm else self.out_channels, ), ) self.input_out_channels = self.out_channels * 2 if (cond_apply_method == 'concat' and condition_dim is not None) else self.out_channels self.out_layers = nn.Sequential( normalization(self.out_channels), nn.SiLU(), nn.Dropout(p=dropout), zero_module( conv_nd(dims, self.input_out_channels, self.out_channels, 3, padding=1) ), # zero out the weights, it seems to help training ) if self.out_channels == channels: self.skip_connection = nn.Identity() elif use_conv: self.skip_connection = conv_nd( dims, channels, self.out_channels, 3, padding=1 ) else: self.skip_connection = conv_nd(dims, channels, self.out_channels, 1) def forward(self, x, emb, cond=None, tab_cond=None): """ Apply the block to a Tensor, conditioned on a timestep embedding. :param x: an [N x C x ...] Tensor of features. :param emb: an [N x emb_channels] Tensor of timestep embeddings. :return: an [N x C x ...] Tensor of outputs. """ return checkpoint( self._forward, (x, emb, cond, tab_cond), self.parameters(), self.use_checkpoint ) def _forward(self, x, emb=None, cond=None, tab_cond=None): if self.updown: in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1] h = in_rest(x) h = self.h_upd(h) x = self.x_upd(x) h = in_conv(h) else: h = self.in_layers(x) if self.use_time_condition: if emb is not None: emb_out = self.emb_layers(emb).type(h.dtype) while len(emb_out.shape) < len(h.shape): emb_out = emb_out[..., None] else: emb_out = None else: emb_out = None if self.condition_dim is not None: if cond is not None: # if cond.shape[-1] == self.condition_dim: # cond_out = self.cond_emb_layers(cond).type(h.dtype) # else: cond_out = cond.type(h.dtype) while len(cond_out.shape) < len(h.shape): cond_out = cond_out[..., None] else: cond_out = None if tab_cond is not None: tab_cond = self.tab_embed(tab_cond).type(h.dtype) while len(tab_cond.shape) < len(h.shape): tab_cond = tab_cond[..., None] tab_cond_out = tab_cond else: tab_cond_out = None else: cond_out = None tab_cond_out = None # if self.use_scale_shift_norm: # out_norm, out_rest = self.out_layers[0], self.out_layers[1:] # scale, shift = th.chunk(emb_out, 2, dim=1) # h = out_norm(h) * (1 + scale) + shift # h = out_rest(h) # else: # h = h + emb_out # h = self.out_layers(h) if self.use_scale_shift_norm and (self.condition_dim is not None): h = self.apply_conditions( h=h, emb=emb_out, cond=cond_out, tab_cond=tab_cond_out, layers=self.out_layers, scale_bias=1, in_channels=self.out_channels, up_down_layer=None, cond_apply_method = self.cond_apply_method, ) # elif self.use_scale_shift_norm and self.use_time_condition: # out_norm, out_rest = self.out_layers[0], self.out_layers[1:] # scale, shift = th.chunk(emb_out, 2, dim=1) # h = out_norm(h) * (1 + scale) + shift # h = out_rest(h) else: # h = h + emb_out h = self.out_layers(h) return (self.skip_connection(x) + h) # * (1 / math.sqrt(2)) def apply_conditions( self, h, emb=None, cond=None, tab_cond=None, layers: nn.Sequential = None, scale_bias: float = 1, in_channels: int = 512, up_down_layer: nn.Module = None, cond_apply_method = None, ): """ apply conditions on the feature maps Args: emb: time conditional (ready to scale + shift) cond: encoder's conditional (ready to scale + shift) tab_cond: tabular conditional (ready to scale + shift) """ two_cond = emb is not None and cond is not None three_cond = emb is not None and cond is not None and tab_cond is not None if emb is not None: # adjusting shapes while len(emb.shape) < len(h.shape): emb = emb[..., None] if two_cond or three_cond: scale_shifts = [emb] if cond is not None: # adjusting shapes while len(cond.shape) < len(h.shape): cond = cond[..., None] if cond_apply_method == 'concat': scale_shifts = [emb] else: # time first scale_shifts = [emb, cond] if tab_cond is not None: while len(tab_cond.shape) < len(h.shape): tab_cond = tab_cond[..., None] scale_shifts.append(tab_cond) else: # "cond" is not used with single cond mode scale_shifts = [emb] # support scale, shift or shift only for i, each in enumerate(scale_shifts): if each is None: # special case: the condition is not provided a = None b = None else: if each.shape[1] == in_channels * 2: a, b = th.chunk(each, 2, dim=1) else: a = each b = None scale_shifts[i] = (a, b) # condition scale bias could be a list if isinstance(scale_bias, Number): biases = [scale_bias] * len(scale_shifts) else: # a list biases = scale_bias # default, the scale & shift are applied after the group norm but BEFORE SiLU pre_layers, post_layers = layers[0], layers[1:] # GN as pre_layer # spilt the post layer to be able to scale up or down before conv # post layers will contain only the conv mid_layers, post_layers = post_layers[:-2], post_layers[-2:] h = pre_layers(h) # scale and shift for each condition for i, (scale, shift) in enumerate(scale_shifts): # if scale is None, it indicates that the condition is not provided if scale is not None: h = h * (biases[i] + scale) if shift is not None: h = h + shift if self.input_out_channels == self.out_channels * 2 and self.cond_apply_method == 'concat': if cond is not None: h = th.cat([h, cond], dim=1) elif cond is None: _zeros = th.zeros_like(h) h = th.cat([h, _zeros], dim=1) h = mid_layers(h) # upscale or downscale if any just before the last conv if up_down_layer is not None: h = up_down_layer(h) h = post_layers(h) return h class AttentionBlock(nn.Module): """ An attention block that allows spatial positions to attend to each other. Originally ported from here, but adapted to the N-d case. https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66. """ def __init__( self, channels, num_heads=1, num_head_channels=-1, use_checkpoint=False, use_new_attention_order=True, ): super().__init__() self.channels = channels if num_head_channels == -1: self.num_heads = num_heads else: assert ( channels % num_head_channels == 0 ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}" self.num_heads = channels // num_head_channels self.use_checkpoint = use_checkpoint self.norm = normalization(channels) self.qkv = conv_nd(1, channels, channels * 3, 1) if use_new_attention_order: # split qkv before split heads self.attention = QKVAttention(self.num_heads) else: # split heads before split qkv self.attention = QKVAttentionLegacy(self.num_heads) self.proj_out = zero_module(conv_nd(1, channels, channels, 1)) def forward(self, x): return checkpoint(self._forward, (x,), self.parameters(), True) def _forward(self, x): b, c, *spatial = x.shape x = x.reshape(b, c, -1) qkv = self.qkv(self.norm(x)) h = self.attention(qkv) h = self.proj_out(h) return (x + h).reshape(b, c, *spatial) def count_flops_attn(model, _x, y): """ A counter for the `thop` package to count the operations in an attention operation. Meant to be used like: macs, params = thop.profile( model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops}, ) """ b, c, *spatial = y[0].shape num_spatial = int(np.prod(spatial)) # We perform two matmuls with the same number of ops. # The first computes the weight matrix, the second computes # the combination of the value vectors. matmul_ops = 2 * b * (num_spatial ** 2) * c model.total_ops += th.DoubleTensor([matmul_ops]) class QKVAttentionLegacy(nn.Module): """ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum( "bct,bcs->bts", q * scale, k * scale ) # More stable with f16 than dividing afterwards weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum("bts,bcs->bct", weight, v) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class QKVAttention(nn.Module): """ A module which performs QKV attention and splits in a different order. """ def __init__(self, n_heads): super().__init__() self.n_heads = n_heads def forward(self, qkv): """ Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x T] tensor after attention. """ bs, width, length = qkv.shape assert width % (3 * self.n_heads) == 0 ch = width // (3 * self.n_heads) q, k, v = qkv.chunk(3, dim=1) scale = 1 / math.sqrt(math.sqrt(ch)) weight = th.einsum( "bct,bcs->bts", (q * scale).view(bs * self.n_heads, ch, length), (k * scale).view(bs * self.n_heads, ch, length), ) # More stable with f16 than dividing afterwards weight = th.softmax(weight.float(), dim=-1).type(weight.dtype) a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length)) return a.reshape(bs, -1, length) @staticmethod def count_flops(model, _x, y): return count_flops_attn(model, _x, y) class UNetModel(nn.Module): """ The full UNet model with attention and timestep embedding, optional SE block. :param in_channels: channels in the input Tensor. :param model_channels: base channel count for the model. :param out_channels: channels in the output Tensor. :param num_res_blocks: number of residual blocks per downsample. :param attention_resolutions: a collection of downsample rates at which attention will take place. May be a set, list, or tuple. For example, if this contains 4, then at 4x downsampling, attention will be used. :param dropout: the dropout probability. :param channel_mult: channel multiplier for each level of the UNet. :param conv_resample: if True, use learned convolutions for upsampling and downsampling. :param dims: determines if the signal is 1D, 2D, or 3D. :param num_classes: if specified (as an int), then this model will be class-conditional with `num_classes` classes. :param use_checkpoint: use gradient checkpointing to reduce memory usage. :param num_heads: the number of attention heads in each attention layer. :param num_heads_channels: if specified, ignore num_heads and instead use a fixed channel width per attention head. :param num_heads_upsample: works with num_heads to set a different number of heads for upsampling. Deprecated. :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. :param resblock_updown: use residual blocks for up/downsampling. :param use_new_attention_order: use a different attention pattern for potentially increased efficiency. """ def __init__( self, image_size, in_channels, model_channels, out_channels, num_res_blocks, attention_resolutions, dropout=0.2, channel_mult=(1, 2, 4, 8), conv_resample=True, # True dims=2, num_classes=None, use_checkpoint=False, use_fp16=False, num_heads=1, num_head_channels=-1, num_heads_upsample=-1, use_scale_shift_norm=True, resblock_updown=False, # False use_new_attention_order=False, use_condition = True, cond_emb_channels = 512, use_tabular_cond = 'bottleneck', # 'bottleneck', 'condition', 'None' tab_cond_dim = 9, use_time_condition = True, with_attention = True, cond_apply_method = 'adaN', ): super().__init__() if num_heads_upsample == -1: num_heads_upsample = num_heads self.image_size = image_size self.in_channels = in_channels self.model_channels = model_channels self.out_channels = out_channels self.num_res_blocks = num_res_blocks self.attention_resolutions = attention_resolutions self.dropout = dropout self.channel_mult = channel_mult self.conv_resample = conv_resample self.num_classes = num_classes self.use_checkpoint = use_checkpoint self.use_fp16 = use_fp16 self.dtype = th.float16 if use_fp16 else th.float32 self.num_heads = num_heads self.num_head_channels = num_head_channels self.num_heads_upsample = num_heads_upsample self.use_condition = use_condition self.use_time_condition = use_time_condition self.use_tabular_cond = use_tabular_cond self.cond_apply_method = cond_apply_method self.condition_dim = None self.cond_emb_channels = None time_embed_dim = model_channels * 4 self.time_embed = nn.Sequential( linear(model_channels, time_embed_dim), nn.SiLU(), linear(time_embed_dim, time_embed_dim), ) if self.use_tabular_cond == 'bottleneck': self.tab_embed_dim = model_channels * channel_mult[-1] self.tab_embed = nn.Sequential( linear(tab_cond_dim, self.tab_embed_dim), nn.SiLU(), linear(self.tab_embed_dim, self.tab_embed_dim), ) if self.use_condition: cond_embed_dim = model_channels * 4 self.condition_dim = cond_embed_dim self.cond_emb_channels = cond_emb_channels if self.num_classes is not None: self.label_emb = nn.Embedding(num_classes, time_embed_dim) ch = input_ch = int(channel_mult[0] * model_channels) # input_in_channels = self.in_channels * 2 if (self.cond_apply_method == 'concat' and self.use_condition) else self.in_channels input_in_channels = self.in_channels self.input_blocks = nn.ModuleList( [TimestepEmbedSequential(conv_nd(dims, input_in_channels, ch, 3, padding=1))] ) self._feature_size = ch input_block_chans = [ch] ds = 1 for level, mult in enumerate(channel_mult): for _ in range(num_res_blocks): layers = [ ResBlock( ch, time_embed_dim, dropout, out_channels=int(mult * model_channels), dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, condition_dim=self.condition_dim, cond_emb_channels=self.cond_emb_channels, use_time_condition=self.use_time_condition, cond_apply_method = self.cond_apply_method, ) ] ch = int(mult * model_channels) if ds in attention_resolutions: if dims == 2: layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=num_head_channels, use_new_attention_order=use_new_attention_order, ) ) elif dims == 3: layers.append( ProjectExciteLayer( ch, reduction_ratio=2, ) ) self.input_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch input_block_chans.append(ch) if level != len(channel_mult) - 1: out_ch = ch self.input_blocks.append( TimestepEmbedSequential( ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, condition_dim=None, cond_emb_channels=self.cond_emb_channels, cond_apply_method = self.cond_apply_method, down=True, ) if resblock_updown else Downsample( ch, conv_resample, dims=dims, out_channels=out_ch ) ) ) ch = out_ch input_block_chans.append(ch) ds *= 2 self._feature_size += ch self.middle_block = TimestepEmbedSequential( ResBlock( ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, condition_dim=self.condition_dim, cond_emb_channels=self.cond_emb_channels, cond_apply_method = self.cond_apply_method, ), AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=num_head_channels, use_new_attention_order=use_new_attention_order, # ) if dims == 2 else ProjectExciteLayer( # ch, # reduction_ratio=2, ) if with_attention else nn.Identity(), ResBlock( ch, time_embed_dim, dropout, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, condition_dim=self.condition_dim, cond_emb_channels=self.cond_emb_channels, cond_apply_method = self.cond_apply_method, ), ) self._feature_size += ch self.output_blocks = nn.ModuleList([]) self.output_upsample_blocks = nn.ModuleList([]) for level, mult in list(enumerate(channel_mult))[::-1]: for i in range(num_res_blocks + 1): ich = input_block_chans.pop() # print('level:', level) if i == 0 and level == (len(list(channel_mult)) - 1) and self.use_tabular_cond == 'bottleneck': in_ch = ch + ich + self.tab_embed_dim else: in_ch = ch + ich layers = [ ResBlock( in_ch, time_embed_dim, dropout, out_channels=int(model_channels * mult), dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, condition_dim=self.condition_dim, cond_emb_channels=self.cond_emb_channels, cond_apply_method = self.cond_apply_method, ) ] ch = int(model_channels * mult) if ds in attention_resolutions: if dims == 2: layers.append( AttentionBlock( ch, use_checkpoint=use_checkpoint, num_heads=num_heads, num_head_channels=num_head_channels, use_new_attention_order=use_new_attention_order, ) ) elif dims == 3: layers.append( ProjectExciteLayer( ch, reduction_ratio=2, ) ) if level and i == num_res_blocks: out_ch = ch upsample_layers = [ ResBlock( ch, time_embed_dim, dropout, out_channels=out_ch, dims=dims, use_checkpoint=use_checkpoint, use_scale_shift_norm=use_scale_shift_norm, condition_dim=None, cond_emb_channels=self.cond_emb_channels, cond_apply_method = self.cond_apply_method, up=True, ) if resblock_updown else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch) ] self.output_upsample_blocks.append(TimestepEmbedSequential(*upsample_layers)) ds //= 2 self.output_blocks.append(TimestepEmbedSequential(*layers)) self._feature_size += ch self.out = nn.Sequential( normalization(ch), nn.SiLU(), zero_module(conv_nd(dims, input_ch, self.out_channels, 3, padding=1)), ) # if use_fp16: # self.convert_to_fp16() def convert_to_fp16(self): """ Convert the torso of the model to float16. """ self.input_blocks.apply(convert_module_to_f16) self.middle_block.apply(convert_module_to_f16) self.output_blocks.apply(convert_module_to_f16) self.output_upsample_blocks.apply(convert_module_to_f16) def convert_to_fp32(self): """ Convert the torso of the model to float32. """ self.input_blocks.apply(convert_module_to_f32) self.middle_block.apply(convert_module_to_f32) self.output_blocks.apply(convert_module_to_f32) self.output_upsample_blocks.apply(convert_module_to_f32) def forward(self, x, timesteps=None, cond=None, tab_cond = None, y=None, return_features=False): """ Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch of timesteps. :param y: an [N] Tensor of labels, if class-conditional. :return: an [N x C x ...] Tensor of outputs. """ assert (y is not None) == ( self.num_classes is not None ), "must specify y if and only if the model is class-conditional" if isinstance(cond, List): len_cond = len(cond) - 1 original_input_cond = cond[0] encoder_cond = cond[1 : len_cond//2 + 1] mid_cond = cond[len_cond//2 + 1] decoder_cond = cond[len_cond//2 + 2:] assert len(encoder_cond) == len(decoder_cond), (len(encoder_cond), len(decoder_cond)) else: original_input_cond = cond if return_features: features = [] features.append(x) hs = [] if timesteps is not None: emb = self.time_embed(timestep_embedding(timesteps, self.model_channels)) else: emb = None if self.num_classes is not None: assert y.shape == (x.shape[0],) emb = emb + self.label_emb(y) if self.use_tabular_cond == 'bottleneck' and tab_cond is not None: assert tab_cond.shape[1] == self.tab_embed[0].in_features self.tab_cond_embedding = self.tab_embed(tab_cond) tab_condition = None elif self.use_tabular_cond == 'condition' and tab_cond is not None: tab_condition = tab_cond else: self.tab_cond_embedding = None tab_condition = None h = x.type(self.dtype) # if self.cond_apply_method == 'concat' and self.use_condition: # if original_input_cond is not None: # h = th.cat([h, original_input_cond], dim=1) # elif original_input_cond is None: # _zeros = th.zeros_like(h) # h = th.cat([h, _zeros], dim=1) # print('input module:') for num, module in enumerate(self.input_blocks): if isinstance(cond, List): h = module(h, emb, encoder_cond[num], tab_condition) else: h = module(h, emb, cond, tab_condition) hs.append(h) if return_features: feature = h features.append(feature) # print('middle module:') if isinstance(cond, List): h = self.middle_block(h, emb, mid_cond, tab_condition) else: h = self.middle_block(h, emb, cond, tab_condition) if return_features: feature = h features.append(feature) if self.use_tabular_cond == 'bottleneck' and tab_cond is not None: self.tab_cond_embedding = self.tab_cond_embedding.reshape(h.shape[0], -1, 1, 1) # expand tabular condition to match the feature map size self.tab_cond_embedding = self.tab_cond_embedding.repeat(1, 1, h.shape[2], h.shape[3]) h = th.cat([h, self.tab_cond_embedding], dim=1) for num, module in enumerate(self.output_blocks): h = th.cat([h, hs.pop()], dim=1) if isinstance(cond, List): h = module(h, emb, decoder_cond[num], tab_condition) else: h = module(h, emb, cond, tab_condition) if return_features: feature = h features.append(feature) if num != 0 and (num + 1) % (self.num_res_blocks + 1) == 0 and ((num + 1) // (self.num_res_blocks + 1) < (len(self.output_upsample_blocks) + 1)): if isinstance(cond, List): h = self.output_upsample_blocks[(num + 1) // (self.num_res_blocks + 1) - 1](h, emb, decoder_cond[num], tab_condition) else: h = self.output_upsample_blocks[(num + 1) // (self.num_res_blocks + 1) - 1](h, emb, cond, tab_condition) h = h.type(x.dtype) pred = self.out(h) if return_features: return pred, features return pred class Return(NamedTuple): pred: th.Tensor
38,114
Python
.py
900
29.418889
157
0.535684
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,724
logger.py
ai-med_PASTA/src/model/logger.py
""" Logger copied from OpenAI baselines to avoid extra RL-based dependencies: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/logger.py """ import os import sys import shutil import os.path as osp import json import time import datetime import tempfile import warnings from collections import defaultdict from contextlib import contextmanager DEBUG = 10 INFO = 20 WARN = 30 ERROR = 40 DISABLED = 50 class KVWriter(object): def writekvs(self, kvs): raise NotImplementedError class SeqWriter(object): def writeseq(self, seq): raise NotImplementedError class HumanOutputFormat(KVWriter, SeqWriter): def __init__(self, filename_or_file): if isinstance(filename_or_file, str): self.file = open(filename_or_file, "wt") self.own_file = True else: assert hasattr(filename_or_file, "read"), ( "expected file or str, got %s" % filename_or_file ) self.file = filename_or_file self.own_file = False def writekvs(self, kvs): # Create strings for printing key2str = {} for (key, val) in sorted(kvs.items()): if hasattr(val, "__float__"): valstr = "%-8.3g" % val else: valstr = str(val) key2str[self._truncate(key)] = self._truncate(valstr) # Find max widths if len(key2str) == 0: print("WARNING: tried to write empty key-value dict") return else: keywidth = max(map(len, key2str.keys())) valwidth = max(map(len, key2str.values())) # Write out the data dashes = "-" * (keywidth + valwidth + 7) lines = [dashes] for (key, val) in sorted(key2str.items(), key=lambda kv: kv[0].lower()): lines.append( "| %s%s | %s%s |" % (key, " " * (keywidth - len(key)), val, " " * (valwidth - len(val))) ) lines.append(dashes) self.file.write("\n".join(lines) + "\n") # Flush the output to the file self.file.flush() def _truncate(self, s): maxlen = 30 return s[: maxlen - 3] + "..." if len(s) > maxlen else s def writeseq(self, seq): seq = list(seq) for (i, elem) in enumerate(seq): self.file.write(elem) if i < len(seq) - 1: # add space unless this is the last one self.file.write(" ") self.file.write("\n") self.file.flush() def close(self): if self.own_file: self.file.close() class JSONOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, "wt") def writekvs(self, kvs): for k, v in sorted(kvs.items()): if hasattr(v, "dtype"): kvs[k] = float(v) self.file.write(json.dumps(kvs) + "\n") self.file.flush() def close(self): self.file.close() class CSVOutputFormat(KVWriter): def __init__(self, filename): self.file = open(filename, "w+t") self.keys = [] self.sep = "," def writekvs(self, kvs): # Add our current row to the history extra_keys = list(kvs.keys() - self.keys) extra_keys.sort() if extra_keys: self.keys.extend(extra_keys) self.file.seek(0) lines = self.file.readlines() self.file.seek(0) for (i, k) in enumerate(self.keys): if i > 0: self.file.write(",") self.file.write(k) self.file.write("\n") for line in lines[1:]: self.file.write(line[:-1]) self.file.write(self.sep * len(extra_keys)) self.file.write("\n") for (i, k) in enumerate(self.keys): if i > 0: self.file.write(",") v = kvs.get(k) if v is not None: self.file.write(str(v)) self.file.write("\n") self.file.flush() def close(self): self.file.close() class TensorBoardOutputFormat(KVWriter): """ Dumps key/value pairs into TensorBoard's numeric format. """ def __init__(self, dir): os.makedirs(dir, exist_ok=True) self.dir = dir self.step = 1 prefix = "events" path = osp.join(osp.abspath(dir), prefix) import tensorflow as tf from tensorflow.python import pywrap_tensorflow from tensorflow.core.util import event_pb2 from tensorflow.python.util import compat self.tf = tf self.event_pb2 = event_pb2 self.pywrap_tensorflow = pywrap_tensorflow self.writer = pywrap_tensorflow.EventsWriter(compat.as_bytes(path)) def writekvs(self, kvs): def summary_val(k, v): kwargs = {"tag": k, "simple_value": float(v)} return self.tf.Summary.Value(**kwargs) summary = self.tf.Summary(value=[summary_val(k, v) for k, v in kvs.items()]) event = self.event_pb2.Event(wall_time=time.time(), summary=summary) event.step = ( self.step ) # is there any reason why you'd want to specify the step? self.writer.WriteEvent(event) self.writer.Flush() self.step += 1 def close(self): if self.writer: self.writer.Close() self.writer = None def make_output_format(format, ev_dir, log_suffix=""): os.makedirs(ev_dir, exist_ok=True) if format == "stdout": return HumanOutputFormat(sys.stdout) elif format == "log": return HumanOutputFormat(osp.join(ev_dir, "log%s.txt" % log_suffix)) elif format == "json": return JSONOutputFormat(osp.join(ev_dir, "progress%s.json" % log_suffix)) elif format == "csv": return CSVOutputFormat(osp.join(ev_dir, "progress%s.csv" % log_suffix)) elif format == "tensorboard": return TensorBoardOutputFormat(osp.join(ev_dir, "tb%s" % log_suffix)) else: raise ValueError("Unknown format specified: %s" % (format,)) # ================================================================ # API # ================================================================ def logkv(key, val): """ Log a value of some diagnostic Call this once for each diagnostic quantity, each iteration If called many times, last value will be used. """ get_current().logkv(key, val) def logkv_mean(key, val): """ The same as logkv(), but if called many times, values averaged. """ get_current().logkv_mean(key, val) def logkvs(d): """ Log a dictionary of key-value pairs """ for (k, v) in d.items(): logkv(k, v) def dumpkvs(): """ Write all of the diagnostics from the current iteration """ return get_current().dumpkvs() def getkvs(): return get_current().name2val def log(*args, level=INFO): """ Write the sequence of args, with no separators, to the console and output files (if you've configured an output file). """ get_current().log(*args, level=level) def debug(*args): log(*args, level=DEBUG) def info(*args): log(*args, level=INFO) def warn(*args): log(*args, level=WARN) def error(*args): log(*args, level=ERROR) def set_level(level): """ Set logging threshold on current logger. """ get_current().set_level(level) def set_comm(comm): get_current().set_comm(comm) def get_dir(): """ Get directory that log files are being written to. will be None if there is no output directory (i.e., if you didn't call start) """ return get_current().get_dir() record_tabular = logkv dump_tabular = dumpkvs @contextmanager def profile_kv(scopename): logkey = "wait_" + scopename tstart = time.time() try: yield finally: get_current().name2val[logkey] += time.time() - tstart def profile(n): """ Usage: @profile("my_func") def my_func(): code """ def decorator_with_name(func): def func_wrapper(*args, **kwargs): with profile_kv(n): return func(*args, **kwargs) return func_wrapper return decorator_with_name # ================================================================ # Backend # ================================================================ def get_current(): if Logger.CURRENT is None: _configure_default_logger() return Logger.CURRENT class Logger(object): DEFAULT = None # A logger with no output files. (See right below class definition) # So that you can still log to the terminal without setting up any output files CURRENT = None # Current logger being used by the free functions above def __init__(self, dir, output_formats, comm=None): self.name2val = defaultdict(float) # values this iteration self.name2cnt = defaultdict(int) self.level = INFO self.dir = dir self.output_formats = output_formats self.comm = comm # Logging API, forwarded # ---------------------------------------- def logkv(self, key, val): self.name2val[key] = val def logkv_mean(self, key, val): oldval, cnt = self.name2val[key], self.name2cnt[key] self.name2val[key] = oldval * cnt / (cnt + 1) + val / (cnt + 1) self.name2cnt[key] = cnt + 1 def dumpkvs(self): if self.comm is None: d = self.name2val else: d = mpi_weighted_mean( self.comm, { name: (val, self.name2cnt.get(name, 1)) for (name, val) in self.name2val.items() }, ) if self.comm.rank != 0: d["dummy"] = 1 # so we don't get a warning about empty dict out = d.copy() # Return the dict for unit testing purposes for fmt in self.output_formats: if isinstance(fmt, KVWriter): fmt.writekvs(d) self.name2val.clear() self.name2cnt.clear() return out def log(self, *args, level=INFO): if self.level <= level: self._do_log(args) # Configuration # ---------------------------------------- def set_level(self, level): self.level = level def set_comm(self, comm): self.comm = comm def get_dir(self): return self.dir def close(self): for fmt in self.output_formats: fmt.close() # Misc # ---------------------------------------- def _do_log(self, args): for fmt in self.output_formats: if isinstance(fmt, SeqWriter): fmt.writeseq(map(str, args)) def get_rank_without_mpi_import(): # check environment variables here instead of importing mpi4py # to avoid calling MPI_Init() when this module is imported for varname in ["PMI_RANK", "OMPI_COMM_WORLD_RANK"]: if varname in os.environ: return int(os.environ[varname]) return 0 def mpi_weighted_mean(comm, local_name2valcount): """ Copied from: https://github.com/openai/baselines/blob/ea25b9e8b234e6ee1bca43083f8f3cf974143998/baselines/common/mpi_util.py#L110 Perform a weighted average over dicts that are each on a different node Input: local_name2valcount: dict mapping key -> (value, count) Returns: key -> mean """ all_name2valcount = comm.gather(local_name2valcount) if comm.rank == 0: name2sum = defaultdict(float) name2count = defaultdict(float) for n2vc in all_name2valcount: for (name, (val, count)) in n2vc.items(): try: val = float(val) except ValueError: if comm.rank == 0: warnings.warn( "WARNING: tried to compute mean on non-float {}={}".format( name, val ) ) else: name2sum[name] += val * count name2count[name] += count return {name: name2sum[name] / name2count[name] for name in name2sum} else: return {} def configure(dir=None, format_strs=None, comm=None, log_suffix=""): """ If comm is provided, average all numerical stats across that comm """ if dir is None: dir = os.getenv("OPENAI_LOGDIR") if dir is None: dir = osp.join( tempfile.gettempdir(), datetime.datetime.now().strftime("openai-%Y-%m-%d-%H-%M-%S-%f"), ) assert isinstance(dir, str) dir = os.path.expanduser(dir) os.makedirs(os.path.expanduser(dir), exist_ok=True) rank = get_rank_without_mpi_import() if rank > 0: log_suffix = log_suffix + "-rank%03i" % rank if format_strs is None: if rank == 0: format_strs = os.getenv("OPENAI_LOG_FORMAT", "stdout,log,csv").split(",") else: format_strs = os.getenv("OPENAI_LOG_FORMAT_MPI", "log").split(",") format_strs = filter(None, format_strs) output_formats = [make_output_format(f, dir, log_suffix) for f in format_strs] Logger.CURRENT = Logger(dir=dir, output_formats=output_formats, comm=comm) if output_formats: log("Logging to %s" % dir) def _configure_default_logger(): configure() Logger.DEFAULT = Logger.CURRENT def reset(): if Logger.CURRENT is not Logger.DEFAULT: Logger.CURRENT.close() Logger.CURRENT = Logger.DEFAULT log("Reset logger") @contextmanager def scoped_configure(dir=None, format_strs=None, comm=None): prevlogger = Logger.CURRENT configure(dir=dir, format_strs=format_strs, comm=comm) try: yield finally: Logger.CURRENT.close() Logger.CURRENT = prevlogger
13,979
Python
.py
392
27.5
132
0.5752
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,725
nn.py
ai-med_PASTA/src/model/nn.py
""" Various utilities for neural networks. """ import math import torch as th import torch.nn as nn # PyTorch 1.7 has SiLU, but we support PyTorch 1.5. class SiLU(nn.Module): def forward(self, x): return x * th.sigmoid(x) class GroupNorm32(nn.GroupNorm): def forward(self, x): return super().forward(x.float()).type(x.dtype) def conv_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D convolution module. """ if dims == 1: return nn.Conv1d(*args, **kwargs) elif dims == 2: return nn.Conv2d(*args, **kwargs) elif dims == 3: return nn.Conv3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}") def linear(*args, **kwargs): """ Create a linear module. """ return nn.Linear(*args, **kwargs) def avg_pool_nd(dims, *args, **kwargs): """ Create a 1D, 2D, or 3D average pooling module. """ if dims == 1: return nn.AvgPool1d(*args, **kwargs) elif dims == 2: return nn.AvgPool2d(*args, **kwargs) elif dims == 3: return nn.AvgPool3d(*args, **kwargs) raise ValueError(f"unsupported dimensions: {dims}") def update_ema(target_params, source_params, rate=0.99): """ Update target parameters to be closer to those of source parameters using an exponential moving average. :param target_params: the target parameter sequence. :param source_params: the source parameter sequence. :param rate: the EMA rate (closer to 1 means slower). """ for targ, src in zip(target_params, source_params): targ.detach().mul_(rate).add_(src, alpha=1 - rate) def zero_module(module): """ Zero out the parameters of a module and return it. """ for p in module.parameters(): p.detach().zero_() return module def scale_module(module, scale): """ Scale the parameters of a module and return it. """ for p in module.parameters(): p.detach().mul_(scale) return module def mean_flat(tensor): """ Take the mean over all non-batch dimensions. """ return tensor.mean(dim=list(range(1, len(tensor.shape)))) def normalization(channels, group_size = 32): """ Make a standard normalization layer. :param channels: number of input channels. :return: an nn.Module for normalization. """ return GroupNorm32(min(group_size, channels), channels) # 32 is the default value def timestep_embedding(timesteps, dim, max_period=10000): """ Create sinusoidal timestep embeddings. :param timesteps: a 1-D Tensor of N indices, one per batch element. These may be fractional. :param dim: the dimension of the output. :param max_period: controls the minimum frequency of the embeddings. :return: an [N x dim] Tensor of positional embeddings. """ half = dim // 2 freqs = th.exp( -math.log(max_period) * th.arange(start=0, end=half, dtype=th.float32) / half ).to(device=timesteps.device) args = timesteps[:, None].float() * freqs[None] embedding = th.cat([th.cos(args), th.sin(args)], dim=-1) if dim % 2: embedding = th.cat([embedding, th.zeros_like(embedding[:, :1])], dim=-1) return embedding def checkpoint(func, inputs, params, flag): """ Evaluate a function without caching intermediate activations, allowing for reduced memory at the expense of extra compute in the backward pass. :param func: the function to evaluate. :param inputs: the argument sequence to pass to `func`. :param params: a sequence of parameters `func` depends on but does not explicitly take as arguments. :param flag: if False, disable gradient checkpointing. """ if flag: args = tuple(inputs) + tuple(params) return CheckpointFunction.apply(func, len(inputs), *args) else: return func(*inputs) class CheckpointFunction(th.autograd.Function): @staticmethod def forward(ctx, run_function, length, *args): ctx.run_function = run_function ctx.input_tensors = list(args[:length]) ctx.input_params = list(args[length:]) with th.no_grad(): output_tensors = ctx.run_function(*ctx.input_tensors) return output_tensors @staticmethod def backward(ctx, *output_grads): ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors] with th.enable_grad(): # Fixes a bug where the first op in run_function modifies the # Tensor storage in place, which is not allowed for detach()'d # Tensors. shallow_copies = [x.view_as(x) for x in ctx.input_tensors] output_tensors = ctx.run_function(*shallow_copies) input_grads = th.autograd.grad( output_tensors, ctx.input_tensors + ctx.input_params, output_grads, allow_unused=True, ) del ctx.input_tensors del ctx.input_params del output_tensors return (None, None) + input_grads
5,088
Python
.py
137
30.80292
88
0.650671
ai-med/PASTA
8
2
1
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,726
optimize_llamacpp_ngl.py
fredlas_optimize_llamacpp_ngl/optimize_llamacpp_ngl.py
import os import struct import subprocess import sys def try_llama_main(ngl, llama_main_path, model_path, desired_context, split_mode, main_gpu, tensor_split): print(f'trying -ngl {ngl}{tensor_split}') cmd = f'{llama_main_path} -m {model_path} -c {desired_context} --split-mode {split_mode}{tensor_split} --main-gpu {main_gpu} --flash-attn -t 4 -ngl {ngl} -n 1 --prompt "if this sentence is in stdout then our ngl was ok"' process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout, stderr = process.communicate() return 'if this sentence is in stdout then our ngl was ok' in stdout.decode() def best_tensor_split(vram_per_gpu, MiB_per_layer, ngl): vram_left = vram_per_gpu[:] remaining_layers = ngl # HACK these overhead estimates are very rough guesses, optimized for 8x22B. # too conservative for smaller models and GPUs? TODO use CUDA0etc buffer size from initial guess for i in range(0, len(vram_left)): vram_left[i] -= 500 vram_left[main_gpu_ind] -= 1000 layers = [0] * len(vram_left) while remaining_layers > 0: target_ind = vram_left.index(max(vram_left)) layers[target_ind] += 1 remaining_layers -= 1 vram_left[target_ind] -= MiB_per_layer # if we think it easily fits, then just let llama.cpp do the default if all(x > 2 * MiB_per_layer for x in vram_left): return '' return ' --tensor-split ' + ','.join(map(str, layers)) def binary_search_most_ngl_possible(low, high, llama_main_path, model_path, desired_context, main_gpu, vram_per_gpu, MiB_per_layer): works = {} ts_strings = {} while low < high: mid = (low + high) // 2 ts_strings[mid] = best_tensor_split(vram_per_gpu, MiB_per_layer, mid) works[mid] = try_llama_main(mid, llama_main_path, model_path, desired_context, 'layer', main_gpu, ts_strings[mid]) if works[mid]: low = mid + 1 else: high = mid # if our answer is below the range we evaluated, indicate not found return low - 1, works.get(low - 1, False), ts_strings.get(low - 1, '') def nvidia_smi_query_quantity(to_query): cmd = f'nvidia-smi --query-gpu={to_query} --format=csv,noheader' process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) stdout, stderr = process.communicate() output_lines = stdout.decode().split() output_ints = [int(s) for s in output_lines if s.isdigit()] return output_ints if len(sys.argv) < 4 or not sys.argv[1].isdigit(): print(f'Usage: python3 {sys.argv[0]} desired_context /path/to/llama.cpp/main /path/to/model.gguf') print(f'\ne.g.: python3 {sys.argv[0]} 8192 ~/llama.cpp/main ~/models/model.gguf') exit(1) desired_context = int(sys.argv[1]) llama_main_path = sys.argv[2] model_path = sys.argv[3] if not os.path.isfile(llama_main_path): print(f'file does not exist: {llama_main_path}') exit(1) main_help_process = subprocess.Popen(f'{llama_main_path} --help', stdout=subprocess.PIPE, shell=True) main_help_stdout, main_help_stderr = main_help_process.communicate() mh = main_help_stdout.decode() if not ('--split-mode' in mh and '--reverse-prompt' in mh): print(f'this file does not appear to be a working llama.cpp "main" executable: {llama_main_path}') exit(1) if not os.path.isfile(model_path): print(f'file does not exist: {model_path}') exit(1) pcie_lanes_per_gpu = nvidia_smi_query_quantity('pcie.link.width.current') vram_per_gpu = nvidia_smi_query_quantity('memory.total') # in MiB nvidia_smi_process = subprocess.Popen('nvidia-smi --query-gpu=name --format=csv,noheader', stdout=subprocess.PIPE, shell=True) nv_stdout, nv_stderr = nvidia_smi_process.communicate() gpu_names = [s for s in nv_stdout.decode().split('\n') if s != ''] vram_bandwidth_table = { 'NVIDIA GeForce RTX 4090': 1008, 'NVIDIA GeForce RTX 4080': 737, 'NVIDIA GeForce RTX 4070 Ti': 672, 'NVIDIA GeForce RTX 4070': 504, 'NVIDIA GeForce RTX 4060 Ti': 288, 'NVIDIA GeForce RTX 4060': 272, 'NVIDIA GeForce RTX 3090': 936, 'NVIDIA GeForce RTX 3080 Ti': 912, 'NVIDIA GeForce RTX 3080': 912, 'NVIDIA GeForce RTX 3070 Ti': 608, 'NVIDIA GeForce RTX 3070': 448, 'NVIDIA GeForce RTX 3060 Ti': 448, 'NVIDIA GeForce RTX 3060': 360, 'NVIDIA GeForce RTX 2080 Ti': 616, 'NVIDIA GeForce RTX 2080': 448, 'NVIDIA GeForce RTX A6000': 768, 'NVIDIA GeForce RTX A4000': 448, 'Tesla P40': 346, 'Tesla P100': 732 } gpu_bandwidths = [vram_bandwidth_table.get(name, 222) for name in gpu_names] for i in range(0, len(gpu_bandwidths)): if gpu_bandwidths[i] == 222: print(f'WARNING! Unrecognized GPU name {gpu_names[i]}. Look up your GPU VRAM bandwidth and put it in the vram_bandwidth_table map in this script (and please open a pull request!), or you might get a suboptimal value for --main-gpu if you have heterogeneous GPUs.') # Pick main GPU: pick highest VRAM bandwidth GPU, with PCIe lanes as tiebreaker best_bw_inds = [i for i, x in enumerate(gpu_bandwidths) if x == max(gpu_bandwidths)] main_gpu_ind = best_bw_inds[0] best_pcie = pcie_lanes_per_gpu[main_gpu_ind] for gpu_ind in best_bw_inds: if pcie_lanes_per_gpu[gpu_ind] > best_pcie: main_gpu_ind = gpu_ind model_layers = 0 model_is_MoE = False with open(model_path, 'rb') as model_file: data = model_file.read(4096) ind_block_count = data.find(b'.block_count') if ind_block_count == -1: print('\nfailed to determine model n_layer from model file block_count') exit(1) model_layers = struct.unpack('<i', data[ind_block_count+16:ind_block_count+20])[0] ind_expert_count = data.find(b'.expert_count') if ind_expert_count > -1: expert_count = struct.unpack('<i', data[ind_expert_count+17:ind_expert_count+21])[0] model_is_MoE = (expert_count > 1) # initial guess, hopefully we can mostly skip binary search model_size_MiB = 1 + os.path.getsize(model_path) // (1024 * 1024) MiB_per_layer = 1 + model_size_MiB // model_layers print(f'model has {model_layers} layers, file size {model_size_MiB}MiB, model_is_MoE: {model_is_MoE}') # we can be pretty sure that if x * mem_per_layer > VRAM, we ain't fittin x layers in VRAM ngl_upperlimit = min(model_layers, sum(vram_per_gpu) // MiB_per_layer) # HACK very crude estimates based on observation total_overhead_guess = 11000 if model_size_MiB > 60000 else (5000 if model_size_MiB > 30000 else 2000) ngl_lowerlimit = min(model_layers, (sum(vram_per_gpu) - total_overhead_guess) // MiB_per_layer) print(f'binary search bounds: low {ngl_lowerlimit} high {ngl_upperlimit+1}') max_ngl_possible, found, tensor_split = binary_search_most_ngl_possible( ngl_lowerlimit, ngl_upperlimit+1, llama_main_path, model_path, desired_context, main_gpu_ind, vram_per_gpu, MiB_per_layer) if not found: print('good ngl not found within guessed binary search area, trying down to 0') max_ngl_possible, found, tensor_split = binary_search_most_ngl_possible( 0, ngl_lowerlimit, llama_main_path, model_path, desired_context, main_gpu_ind, vram_per_gpu, MiB_per_layer) if not found: print("Not even -ngl 0 works. It looks like you can't run this model. Sorry.") exit(1) split_mode = 'layer' if model_is_MoE or max_ngl_possible < model_layers else 'row' # TODO do we need to confirm --split-mode row can run? print(f'\nRun llama.cpp with these arguments:\n-m {model_path} -c {desired_context} --split-mode {split_mode}{tensor_split} --main-gpu {main_gpu_ind} --flash-attn -t 4 -ngl {max_ngl_possible}')
7,920
Python
.py
143
48.881119
268
0.665163
fredlas/optimize_llamacpp_ngl
8
0
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,727
plt_style.py
mikelma_componet/utils/plt_style.py
import matplotlib.pyplot as plt import matplotlib import colormaps as cmaps def style(fig, ax=None, grid=True, legend=True, legend_title=None, legend_ncols=1, force_sci_x=False, force_sci_y=False, font=3, colormap=cmaps.greenorange_12, legend_shrink=0.1, ax_math_ticklabels=True, y_spine=False): if colormap is not None: plt.set_cmap(colormap) # remove lateral spines ax = ax if ax is not None else plt.gca() ax.spines['right'].set_visible(False) ax.spines['top'].set_visible(False) ax.spines['left'].set_visible(y_spine) if ax_math_ticklabels: ax.ticklabel_format(useMathText=True) # axis sci notation if force_sci_x or force_sci_y: ax.ticklabel_format(useOffset=False) ax.ticklabel_format(style='sci', axis='x' if force_sci_x else 'y', scilimits=(0,0)) # set spine and tick width and color axis_color = "lightgrey" ax.spines["bottom"].set(linewidth=1.3, color=axis_color) ax.spines["left"].set(linewidth=1.3, color=axis_color) ax.xaxis.set_tick_params(width=1.3, color=axis_color) yc = axis_color if y_spine else "white" ax.yaxis.set_tick_params(width=1.3, color=yc) if legend: l = fig.legend(title=legend_title, fancybox=False, frameon=False, loc="outside lower center", ncols=legend_ncols) # Shrink current axis's height by 10% on the bottom p = legend_shrink # % box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * p, box.width, box.height * (1-p)]) if grid: ax.grid(True, axis='y', alpha=0.2, linestyle='-') ax.yaxis.set_tick_params(size=0)
1,715
Python
.py
36
39.722222
219
0.64632
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,728
impl.py
mikelma_componet/componet/impl.py
import torch import torch.nn as nn import torch.nn.functional as F from torch.distributions.categorical import Categorical import numpy as np import math def get_position_encoding(seq_len, d, n=10_000): """ Returns the positional encoding matrix for the given parameters. seq_len -- Length of the sequence (number of positional encodings). d -- Dimension of the encodings. n -- User defined scalar, set to 10k in "Attention is all you need". Default: 10_000. """ P = np.zeros((seq_len, d)) for k in range(seq_len): for i in np.arange(int(d / 2)): denominator = np.power(n, 2 * i / d) P[k, 2 * i] = np.sin(k / denominator) P[k, 2 * i + 1] = np.cos(k / denominator) return P def logit2prob(logits): return F.softmax(logits, dim=1) class Identity: """A callable object that returns it's input. Although this class might seem trivial, it fixes the issue of saving CompoNet and FirstModuleWrapper modules using `torch.save`, as it cannot serialize lambda functions. See: https://stackoverflow.com/questions/70608810/pytorch-cant-pickle-lambda """ def __call__(self, arg, **kwargs): return arg class CompoNet(nn.Module): def __init__( self, previous_units: [nn.Module], input_dim: int, hidden_dim: int, out_dim: int, internal_policy: nn.Module, ret_probs: bool, encoder: nn.Module = None, device="cuda" if torch.cuda.is_available() else "cpu", proj_bias: bool = True, att_heads_init: object = Identity(), ): """CompoNet initializer. Keyword arguments: previous_units -- List of the previous CompoNet modules. input_dim -- Dimension of the input state vector, or when using an encoder, the output dimension of the encoder. hidden_dim -- Hidden dimension of the model. out_dim -- Dimension of the output vector (should be equal to the number of actions). internal_policy -- The model to be used as internal policy, it's input size must match with `input_dim+hidden_dim` and it's output `out_dim`. ret_probs -- If `True`, the module returns probability vectors, else logits. encoder -- Optionally, the user can define a `nn.Module` to use as the encoder for the current module. The identity function is used if no value is given. device -- Device to operate on. Set to `cuda` if a gpu is found and no user defined value is given, else `cpu`. proj_bias -- Whether to activate bias in the linear transformations of the attention heads. True by default. att_heads_init -- Initialization of the linear transformations of the attention heads. PyTorch default initializer is used by default. """ super(CompoNet, self).__init__() self.hidden_dim = hidden_dim self.out_dim = out_dim self.ret_probs = ret_probs self.internal_policy = internal_policy self.encoder = encoder if encoder is not None else Identity() self.att_temp = np.sqrt( hidden_dim ) # pre-compute the temperature of the attention # this attribute is internally used by CompoNet to distinguish between the current # module and previous ones self.is_prev = False # linear transformations of the output attention head self.headout_wq = att_heads_init( nn.Linear(input_dim, hidden_dim, bias=proj_bias) ) self.headout_wk = att_heads_init(nn.Linear(out_dim, hidden_dim, bias=proj_bias)) # linear transformations of the input attention head self.headin_wq = att_heads_init( nn.Linear(input_dim, hidden_dim, bias=proj_bias) ) self.headin_wk = att_heads_init(nn.Linear(out_dim, hidden_dim, bias=proj_bias)) self.headin_wv = att_heads_init(nn.Linear(out_dim, hidden_dim, bias=proj_bias)) # pre-compute the positional encodings for the input attention head n_prev = len(previous_units) pe1 = torch.tensor( get_position_encoding(seq_len=n_prev + 1, d=out_dim), dtype=torch.float32, device=device, ) # (n_prev+1, out_dim) self.pe1 = pe1[None, :, :] # (1, n_prev+1, out_dim) # if needed, obtain the positional encoding for the output attention head if n_prev >= 2: self.pe0 = self.pe1[:, :-1, :] # (1, n_prev, out_dim) else: self.pe0 = None # prepare previous units for unit in previous_units: # remove previous units if some if hasattr(unit, "previous_units"): del unit.previous_units unit.is_prev = True unit.eval() # freeze all the parameters for param in unit.parameters(): param.requires_grad = False # join all previous units into a single sequential model self.previous_units = nn.Sequential(*previous_units) def _forward_headout(self, s, phi): """Compute the output attention head. Returns the result of the attention head and the employed attention weights. s -- The current state representation. phi -- The matrix with the results of the previous modules. """ # compute the query, keys and values query = self.headout_wq(s) # add pos. enc. and compute K transformation keys = self.headout_wk(phi + self.pe0 if self.pe0 is not None else phi) values = phi # size: (batch, 1, num_policies) w = torch.matmul( # size: (batch, 1, hidden_dim) query[:, None, :], # size: (batch, hidden_dim, num_policies) keys.permute(0, 2, 1), # transpose keys matrix ) # get attention weights att = F.softmax(w / self.att_temp, dim=-1) # size: (batch_size, 1, out_dim) att_dot_val = torch.matmul(att, values) # att_dot_val = att_dot_val[:, 0, :] # remove extra dim return att_dot_val, att def _get_internal_policy(self, s, phi): """Compute the input attention head and the internal policy. Returns the result of the internal policy and the employed attention weights. s -- The current state representation. phi -- The matrix with the results of the previous modules and the result of the output attention head. """ # obtain the elements of the dot-product attentionx query = self.headin_wq(s) values = self.headin_wv(phi) keys = self.headin_wk(phi + self.pe1) # size: (batch, 1, num_policies) w = torch.matmul( # size: (batch, 1, hidden_dim) query[:, None, :], # size: (batch, hidden_dim, num_policies) keys.permute(0, 2, 1), # transpose keys matrix ) # get attention weights att = F.softmax(w / self.att_temp, dim=-1) # size: (batch_size, 1, out_dim) att_dot_val = torch.matmul(att, values) att_dot_val = att_dot_val[:, 0, :] # remove extra dim # concat the current state and the result of the input attention head policy_in = torch.hstack([att_dot_val, s]) # pass forward the internal policy policy_out = self.internal_policy(policy_in) return policy_out, att def forward( self, s, ret_encoder_out=False, return_atts=False, ret_int_pol=False, ret_head_out=False, prevs_to_noise=0, ): """Forward pass of the CompoNet unit. This method has two behaviors depending on whether the module is the last module of CompoNet or not. If it is not the last one, the method takes a matrix with the outputs of the preceding modules and the current state as input, and returns the same tuple but with the output of the module appended to the input matrix. In this case, all keyword arguments are ignored. This mode of operation is only intended to be used internally by CompoNet, and you might not need to care about it unless you are hacking with the code. If the module is the last one (the one operating in the current task), the method takes the current state as the input, and runs the whole CompoNet network to get the final result of the model. In this case, the method returns the vector with the output of the model and the matrix with the outputs of preceding modules, plus, some other values controlled by the method's keyword arguments. Keyword arguments: s -- Input state. Note that if an encoder was given, CompoNet will process this tensor with the encoder before using it. ret_encoder_out -- If true, the output of the encoder is appended to the return values. Default: False. return_atts -- If true, the att. values of the input and output att. heads are returned. Default: False. ret_int_pol -- If true, the output of the internal policy is returned. Default: False. ret_head_out -- If true, the result of the output attention head is returned. Default: False prevs_to_noise -- If >0, the output of the first `prevs_to_noise` number of modules is replaced with random noise. This is intended to be used in ablation experiments. Returns: pi -- Output vector of the CompoNet model. phi -- The matrix of previous policies with the current one stacked as the last row. (optionals, in order) enc_out -- The output of the encoder. att_head_in -- Attention values of the input attention head. att_head_out -- Attention values of the output attention head. ret_head_out -- Output of the output attention head. int_pol -- Output of the internal policy """ # obtain the outputs of preceding modules (the phi matrix) if not self.is_prev: # if it's the last module with torch.no_grad(): # get the output of the previous modules in the Phi matrix phi, _s = self.previous_units(s) # this code block is only used for ablation purposes, where the output of # the first `prevs_to_noise` number of modules is replaced with random noise if prevs_to_noise > 0: # sample from a uniform dirichlet if we're dealing with probability vectors if self.ret_probs: m = torch.distributions.Dirichlet( torch.tensor([1 / self.out_dim] * self.out_dim) ) r = m.sample(sample_shape=[phi.size(0), prevs_to_noise]) else: # if we're using logits, sample from a 0,1 normal distribution r = torch.randn((phi.size(0), prevs_to_noise, phi.size(-1))) phi[:, :prevs_to_noise, :] = r else: assert type(s) == tuple, "Input to a previous unit must be a tuple (phi, s)" phi, s = s # phi: (batch, num prev, out dim), s: (batch, input dim) hs = self.encoder(s) # compute the result of the output att. head out_head, att_head_out = self._forward_headout(hs, phi) # get the output of the internal policy int_pol_phi = torch.cat( [phi, out_head], dim=1 ) # concat in the num_prev dimension logits, att_head_in = self._get_internal_policy(hs, int_pol_phi) # compute the final output of the module out_head = out_head[:, 0, :] # (batch, 1, out_dim) -> (batch, out_dim) out = out_head + logits # normalize output if necessary if self.ret_probs: out = logit2prob(out) # add the resulting policy to the phi matrix out = out[:, None, :] # out: (batch, 1, out_dim) phi = torch.cat([phi, out], dim=1) # concat in the num_prev dimension if self.is_prev: return phi, s out = out[:, 0, :] # (batch, out_dim) # build the return value depending on the selected options ret_vals = [out, phi] if ret_encoder_out: ret_vals.append(hs) if return_atts: ret_vals += [att_head_in, att_head_out] if ret_int_pol: ret_vals.append(logits) if ret_head_out: ret_vals.append(out_head) return ret_vals class FirstModuleWrapper(nn.Module): """This class servers as a wrapper for the first module of CompoNet. The wrapper is around a PyTorch's `nn.Module` that takes as an input states of the environment and returns an output of the same shape as the rest of the CompoNet modules. For example, in atari, this model would take an image as input and it'd output a logit vector over the action space. **IMPORTANT:** The wrapped module MUST NOT return normalized outputs, the normalization is done by the wrapper when setting `ret_probs=True`. """ def __init__( self, model: nn.Module, ret_probs: bool, encoder: object = Identity(), transform_output: object = Identity(), ): """FirstModuleWrapper initializer. Keyword arguments: model -- The `nn.Module` to wrap. ret_probs -- A boolean specifying whether to normalize the output of the model or not. encoder -- An optional encoder model to process the inputs for the wrapped model. The identity function is used by default. transform_output -- A callable object that can be used to transform the output of the wrapped model. """ super(FirstModuleWrapper, self).__init__() self.model = model self.encoder = encoder self.is_prev = False self.ret_probs = ret_probs self.transform_output = transform_output def forward(self, x, ret_encoder_out=False): h = self.encoder(x) v = self.transform_output(self.model(h)) pi = logit2prob(v) if self.ret_probs else v phi = pi[None, :, :] # (1, batch size, out dim) phi = phi.permute(1, 0, 2) # (batch size, 1, out dim) if self.is_prev: return phi, x else: if ret_encoder_out: return pi, phi, h return pi, phi if __name__ == "__main__": # an example of the usage of the CompoNet class input_dim = 128 hidden_dim = 512 out_dim = 6 batch_size = 3 num_units = 4 def internal_policy_gen(): return nn.Sequential( nn.Linear(input_dim + hidden_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, out_dim), ) first_module = nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, out_dim), ) dummy = FirstModuleWrapper(first_module, ret_probs=True) prevs = [dummy] for _ in range(num_units - 1): unit = CompoNet( previous_units=prevs, input_dim=input_dim, hidden_dim=hidden_dim, out_dim=out_dim, internal_policy=internal_policy_gen(), ret_probs=True, ) prevs.append(unit) print(unit) x = torch.rand((batch_size, input_dim)) print( f"\nInput dim: {input_dim}, Output dim: {out_dim}, Num units: {num_units}, Batch size: {batch_size}" ) print(f"\nInput tensor: {x.size()}") pi, phi = unit(x) print(f"Output policy: {pi.size()}") print(f"Output Phi matrix: {phi.size()}")
16,153
Python
.py
337
37.910979
133
0.602884
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,729
plot_dino_vs_cnn.py
mikelma_componet/experiments/atari/plot_dino_vs_cnn.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from matplotlib.lines import Line2D from argparse import ArgumentParser import sys sys.path.append("../../") from utils import plt_style def parse_args(): # fmt: off parser = ArgumentParser() parser.add_argument("--dirname", type=str, default="data/dino_vs_cnn", help="directory where the CSV data of the experiments is stored") # fmt: on return parser.parse_args() def ma(x, w): return np.convolve(x, np.ones(w), "valid") / w def smooth(x, y, num_points, ma_num=10, idxs=None): # apply moving average smoothing y = ma(y, ma_num) x = x[0 : len(y)] # only select some points idx = ( np.linspace(0, len(y) - 1, num=num_points, dtype=np.int64) if idxs is None else idxs ) y = y[idx] x = x[idx] return x, y def select_valid(df, data_lbl): val_idx = ~pd.isna(df[data_lbl]) y = np.array(df[data_lbl][val_idx]) x = np.array(df["global_step"][val_idx]) return x, y def plot_ep_rets(fname): df = pd.read_csv(fname) cnn_mean_cols = [] dino_mean_cols = [] for col in df.columns: if col.endswith("(DINO-3 layers) - charts/episodic_return"): dino_mean_cols.append(col) elif col.endswith("(CNN) - charts/episodic_return"): cnn_mean_cols.append(col) plt.rcParams.update({"font.size": 13}) fig = plt.figure() plt_style.style(fig, legend=False) for alg, alg_cols in [("CNN", cnn_mean_cols), ("DINO", dino_mean_cols)]: for col in alg_cols: x, y = select_valid(df, col) x, y = smooth(x, y, num_points=100, ma_num=100) plt.plot(x, y, c="tab:blue" if alg == "CNN" else "tab:orange", alpha=0.7) custom_lines = [ Line2D([0], [0], color="tab:blue"), Line2D([0], [0], color="tab:orange"), ] plt.legend( custom_lines, ["CNN", "DINO"], fancybox=False, frameon=False, loc="lower right" ) plt.xlabel("Timestep") plt.ylabel("Episodic return") plt.savefig("dino_vs_cnn.pdf") plt.show() def plot_times(fname, col_names="Name", col_times="Relative Time (Process)"): df = pd.read_csv(fname) t_cnn = [] t_dino = [] for name in df[col_names]: t = float(df[df[col_names] == name][col_times].iloc[0]) t /= 60 * 60 if "CNN" in name: t_cnn.append(t) elif "DINO" in name: t_dino.append(t) plt.rcParams.update({"font.size": 13}) fig = plt.figure(figsize=(4, 5)) plt_style.style(fig, legend=False) sns.barplot(pd.DataFrame({"CNN": t_cnn, "DINO": t_dino})) plt.ylabel("Elapsed time (hours)") plt.savefig("dino_vs_cnn_times.pdf") plt.show() if __name__ == "__main__": args = parse_args() plot_ep_rets(fname=f"{args.dirname}/ep_rets.csv") plot_times(fname=f"{args.dirname}/times.csv")
2,947
Python
.py
86
28.44186
87
0.607118
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,730
plot_ablation_input_head.py
mikelma_componet/experiments/atari/plot_ablation_input_head.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D import matplotlib.colors as mcolors import sys from argparse import ArgumentParser sys.path.append("../../") from utils import plt_style def parse_args(): # fmt: off parser = ArgumentParser() parser.add_argument("--dirname", type=str, default="data/input_head_ablation", help="directory where the CSV data of the experiments is stored") # fmt: on return parser.parse_args() def smooth_curve(df, data_col, idx_col="global_step", chunksize=None, w=None): idx = ~df[data_col].isnull() y = df[data_col][idx].values x = df[idx_col][idx].values # compute the average of chunks if chunksize is not None: n = x.shape[0] x = np.array([c.mean() for c in np.array_split(x, n // chunksize)]) y = np.array([c.mean() for c in np.array_split(y, n // chunksize)]) # second smotthing with a moving average if w is not None: x = np.convolve(x, np.ones(w), "valid") / w y = np.convolve(y, np.ones(w), "valid") / w return x, y def plot_ep_ret(fig, ax, path="data/ep_ret.csv", path_ref=None): df = pd.read_csv(path) cols = df.columns col_method = cols[ cols.str.endswith("episodic_return") & cols.str.contains("No ablation") ][0] col_ablated = cols[ cols.str.endswith("episodic_return") & cols.str.contains("Ablated") ][0] if path_ref is None: path_ref = path[:-4] + "_main_exp.csv" df_ref = pd.read_csv(path_ref) cols = df_ref.columns col_ref = cols[ (cols.str.contains(" cnn-simple ")) & (cols.str.endswith("episodic_return")) ][0] x, y_ref = smooth_curve(df_ref, data_col=col_ref, chunksize=100, w=10) x_min, y_min = smooth_curve(df_ref, data_col=col_ref + "__MIN", chunksize=100, w=10) x_max, y_max = smooth_curve(df_ref, data_col=col_ref + "__MAX", chunksize=100, w=10) ax.plot(x, y_ref, label="Baseline") ax.fill_between(x, y_min, y_max, alpha=0.3) x, y_method = smooth_curve(df, data_col=col_method, chunksize=100, w=10) x_min, y_min = smooth_curve(df, data_col=col_method + "__MIN", chunksize=100, w=10) x_max, y_max = smooth_curve(df, data_col=col_method + "__MAX", chunksize=100, w=10) ax.plot( x, y_method, label="CompoNet", marker="X", markevery=len(x) // 5, markeredgecolor="white", markersize=10, ) ax.fill_between(x, y_min, y_max, alpha=0.3) x, y_ref = smooth_curve(df, data_col=col_ablated, chunksize=100, w=10) x_min, y_min = smooth_curve(df, data_col=col_ablated + "__MIN", chunksize=100, w=10) x_max, y_max = smooth_curve(df, data_col=col_ablated + "__MAX", chunksize=100, w=10) ax.plot( x, y_ref, label="Ablated", marker="d", markevery=len(x) // 5, markeredgecolor="white", markersize=10, ) ax.fill_between(x, y_min, y_max, alpha=0.3) ax.set_xlabel("Timestep\n(i)") ax.set_ylabel("Episodic return") plt_style.style(fig, ax, legend=False) ax.legend(fancybox=False, frameon=False, loc="upper left", bbox_to_anchor=(1, 1)) # textstr = "(i)" # props = dict(boxstyle="round", facecolor="wheat", alpha=0.5) # ax.text( # 0.05, # 1.05, # textstr, # transform=ax.transAxes, # fontsize=14, # verticalalignment="top", # bbox=props, # ) def plot_matches(fig, ax, path="data/matches.csv"): df = pd.read_csv(path) variants = ["No ablation", "Ablated"] variant_styles = ["solid", "dashed"] labels = ["Out = Out head", "Out = Int. pol.", "Out head = Int. pol."] markers = [None, "D", "o"] num_markers = 5 c = list(mcolors.TABLEAU_COLORS) colors = [c[0], c[1], c[3]] for variant, linestyle in zip(variants, variant_styles): cols = df.columns[df.columns.str.contains(variant)] col_out_m_head_out = cols[cols.str.endswith("out_matches_head_out")][0] col_out_m_int_pol = cols[cols.str.endswith("out_matches_int_pol")][0] col_int_pol_m_head = cols[cols.str.endswith("int_pol_matches_head")][0] cols = [col_out_m_head_out, col_out_m_int_pol, col_int_pol_m_head] for i, (col, lbl) in enumerate(zip(cols, labels)): x, y = smooth_curve(df, data_col=col, chunksize=5, w=10) x_min, y_min = smooth_curve(df, data_col=col + "__MIN", chunksize=5, w=10) _, y_max = smooth_curve(df, data_col=col + "__MAX", chunksize=5, w=10) color = colors[i % len(labels)] ax.plot( x, y, label=lbl, linestyle=linestyle, color=color, marker=markers[i], markersize=8, markevery=len(x) // num_markers, markeredgecolor="white", ) ax.fill_between(x_min, y_min, y_max, alpha=0.1, color=color) ax.set_xlabel("Timestep\n(ii)") ax.set_ylabel("Matching rate") plt_style.style(fig, ax, legend=False) # ax.legend(fancybox=False, frameon=False) c = colors + ["black"] * 2 styles = ["solid"] * (len(c) - 1) + ["dashed"] custom_lines = [ Line2D([0], [0], color=c[i], linestyle=styles[i]) for i in range(len(c)) ] custom_lines[1].set(marker=markers[1], markersize=8, markeredgecolor="white") custom_lines[2].set(marker=markers[2], markersize=8, markeredgecolor="white") ax.legend( custom_lines, labels + ["Original", "Ablated"], fancybox=False, frameon=False, loc="upper left", bbox_to_anchor=(1, 1), ) # textstr = "(ii)" # props = dict(boxstyle="round", facecolor="wheat", alpha=0.5) # ax.text( # 0.05, # 1.05, # textstr, # transform=ax.transAxes, # fontsize=14, # verticalalignment="top", # bbox=props, # ) def plot_input_attention(fig, ax, path="data/input_attentions.csv"): df = pd.read_csv(path) cols = df.columns num_atts = 6 for i in range(num_atts): col = cols[cols.str.endswith(f"att_in_{i}")][0] x, y = smooth_curve(df, data_col=col, chunksize=10, w=None) _, y_min = smooth_curve(df, data_col=col + "__MIN", chunksize=10, w=None) _, y_max = smooth_curve(df, data_col=col + "__MAX", chunksize=10, w=None) lbl = f"Prev. {i}" if i < num_atts - 1 else "Out head" marker = None if i != 4 else "*" marker = "o" if lbl == "Out head" else marker s = 15 if marker == "*" else 8 lbl = "Inf. Mod." if i == 4 else lbl ax.plot( x, y, label=lbl, marker=marker, markevery=len(x) // 5, markeredgecolor="white", markersize=s, ) ax.fill_between(x, y_min, y_max, alpha=0.1) ax.set_ylim(0, 1) ax.set_xlabel("Timestep\n(iii)") ax.set_ylabel(f"In. head's attention val.") plt_style.style(fig, ax, legend=False) ax.legend(fancybox=False, frameon=False, loc="upper left", bbox_to_anchor=(1, 1)) # place a text box in upper left in axes coords # textstr = "(iii)" # props = dict(boxstyle="round", facecolor="wheat", alpha=0.5) # ax.text( # 0.05, # 1.05, # textstr, # transform=ax.transAxes, # fontsize=14, # verticalalignment="top", # bbox=props, # ) def plot_output_attention(fig, ax, path="data/output_attentions.csv"): df = pd.read_csv(path) cols = df.columns num_atts = 5 variants = ["No ablation", "Ablated"] variant_styles = ["solid", "dashed"] labels = [f"Prev. {i}" for i in range(num_atts)] colors = list(mcolors.TABLEAU_COLORS) for variant, style in zip(variants, variant_styles): for i in range(num_atts): col = cols[cols.str.endswith(f"att_out_{i}") & cols.str.contains(variant)][ 0 ] x, y = smooth_curve(df, data_col=col, chunksize=10, w=None) _, y_min = smooth_curve(df, data_col=col + "__MIN", chunksize=10, w=None) _, y_max = smooth_curve(df, data_col=col + "__MAX", chunksize=10, w=None) marker = "*" if i == num_atts - 1 else None ax.plot( x, y, linestyle=style, color=colors[i], marker=marker, markevery=len(x) // 6, markeredgecolor="white", markersize=15, ) ax.fill_between(x, y_min, y_max, alpha=0.1, color=colors[i]) ax.set_ylim(0, 1) ax.set_xlabel("Timestep\n(iv)") ax.set_ylabel(f"Out head's attention val.") plt_style.style(fig, ax, legend=False) # ax.legend(loc="center right", fancybox=False, frameon=False) c = colors[:num_atts] + ["black"] * 2 styles = ["solid"] * (num_atts + 1) + ["dashed"] custom_lines = [ Line2D([0], [0], color=c[i], linestyle=styles[i]) for i in range(len(c)) ] custom_lines[-3].set(marker="*", markeredgecolor="white", markersize=15) ax.legend( custom_lines, labels + ["Original", "Ablated"], loc="upper left", bbox_to_anchor=(1, 1), fancybox=False, frameon=False, ) # textstr = "(iv)" # props = dict(boxstyle="round", facecolor="wheat", alpha=0.5) # ax.text( # 0.05, # 1.1, # textstr, # transform=ax.transAxes, # fontsize=14, # verticalalignment="top", # bbox=props, # ) if __name__ == "__main__": args = parse_args() plt.rcParams.update({"font.size": 12}) fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(12, 6)) plot_ep_ret(fig, axs[0, 0], path=f"{args.dirname}/ep_ret.csv") plot_matches(fig, axs[0, 1], path=f"{args.dirname}/matches.csv") plot_input_attention(fig, axs[1, 0], path=f"{args.dirname}/input_head.csv") plot_output_attention(fig, axs[1, 1], path=f"{args.dirname}/output_head.csv") plt.tight_layout(rect=[0.12, 0, 1.0, 1.0]) plt.savefig(f"ablation_input_head.pdf") plt.show()
10,255
Python
.py
264
31.522727
88
0.574432
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,731
run_ppo.py
mikelma_componet/experiments/atari/run_ppo.py
# docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/ppo/#ppo_ataripy import os import random import time from dataclasses import dataclass import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.optim as optim import tyro from typing import Literal, Tuple, Optional import pathlib from torch.utils.tensorboard import SummaryWriter from stable_baselines3.common.atari_wrappers import ( # isort:skip ClipRewardEnv, EpisodicLifeEnv, FireResetEnv, MaxAndSkipEnv, NoopResetEnv, ) from models import ( CnnSimpleAgent, DinoSimpleAgent, CnnCompoNetAgent, ProgressiveNetAgent, PackNetAgent, ) @dataclass class Args: # Model type model_type: Literal[ "cnn-simple", "cnn-simple-ft", "dino-simple", "cnn-componet", "prog-net", "packnet", ] """The name of the model to use as agent.""" dino_size: Literal["s", "b", "l", "g"] = "s" """Size of the dino model (only needed when using dino)""" save_dir: str = None """Directory where the trained model will be saved. If not provided, the model won't be saved""" prev_units: Tuple[pathlib.Path, ...] = () """Paths to the previous models. Only used when employing a CompoNet or cnn-simple-ft (finetune) agent""" mode: int = None """Playing mode for the Atari game. The default mode is used if not provided""" componet_finetune_encoder: bool = False """Whether to train the CompoNet's encoder from scratch of finetune it from the encoder of the previous task""" total_task_num: Optional[int] = None """Total number of tasks, required when using PackNet""" prevs_to_noise: Optional[int] = 0 """Number of previous policies to set to randomly selected distributions, only valid when model_type is `cnn-componet`""" # Experiment arguments exp_name: str = os.path.basename(__file__)[: -len(".py")] """the name of this experiment""" seed: int = 1 """seed of the experiment""" torch_deterministic: bool = True """if toggled, `torch.backends.cudnn.deterministic=False`""" cuda: bool = True """if toggled, cuda will be enabled by default""" track: bool = False """if toggled, this experiment will be tracked with Weights and Biases""" wandb_project_name: str = "ppo-atari" """the wandb's project name""" wandb_entity: str = None """the entity (team) of wandb's project""" capture_video: bool = False """whether to capture videos of the agent performances (check out `videos` folder)""" # Algorithm specific arguments env_id: str = "BreakoutNoFrameskip-v4" """the id of the environment""" total_timesteps: int = int(1e6) """total timesteps of the experiments""" learning_rate: float = 2.5e-4 """the learning rate of the optimizer""" num_envs: int = 8 """the number of parallel game environments""" num_steps: int = 128 """the number of steps to run in each environment per policy rollout""" anneal_lr: bool = True """Toggle learning rate annealing for policy and value networks""" gamma: float = 0.99 """the discount factor gamma""" gae_lambda: float = 0.95 """the lambda for the general advantage estimation""" num_minibatches: int = 4 """the number of mini-batches""" update_epochs: int = 4 """the K epochs to update the policy""" norm_adv: bool = True """Toggles advantages normalization""" clip_coef: float = 0.1 """the surrogate clipping coefficient""" clip_vloss: bool = True """Toggles whether or not to use a clipped loss for the value function, as per the paper.""" ent_coef: float = 0.01 """coefficient of the entropy""" vf_coef: float = 0.5 """coefficient of the value function""" max_grad_norm: float = 0.5 """the maximum norm for the gradient clipping""" target_kl: float = None """the target KL divergence threshold""" # to be filled in runtime batch_size: int = 0 """the batch size (computed in runtime)""" minibatch_size: int = 0 """the mini-batch size (computed in runtime)""" num_iterations: int = 0 """the number of iterations (computed in runtime)""" def make_env(env_id, idx, capture_video, run_name, mode=None, dino=False): def thunk(): if mode is None: env = gym.make(env_id) else: env = gym.make(env_id, mode=mode) if capture_video and idx == 0: env = gym.wrappers.RecordVideo(env, f"videos/{run_name}") env = gym.wrappers.RecordEpisodeStatistics(env) if capture_video: if idx == 0: env = gym.wrappers.RecordVideo(env, f"videos/{run_name}") env = NoopResetEnv(env, noop_max=30) env = MaxAndSkipEnv(env, skip=4) env = EpisodicLifeEnv(env) if "FIRE" in env.unwrapped.get_action_meanings(): env = FireResetEnv(env) env = ClipRewardEnv(env) if not dino: env = gym.wrappers.ResizeObservation(env, (84, 84)) env = gym.wrappers.GrayScaleObservation(env) else: env = gym.wrappers.ResizeObservation(env, (224, 224)) env = gym.wrappers.FrameStack(env, 4) return env return thunk if __name__ == "__main__": args = tyro.cli(Args) args.batch_size = int(args.num_envs * args.num_steps) args.minibatch_size = int(args.batch_size // args.num_minibatches) args.num_iterations = args.total_timesteps // args.batch_size m = f"_{args.mode}" if args.mode is not None else "" run_name = f"{args.env_id.replace('/', '-')}{m}__{args.model_type}__{args.exp_name}__{args.seed}" print("*** Run's name:", run_name) if args.track: import wandb wandb.init( project=args.wandb_project_name, entity=args.wandb_entity, sync_tensorboard=True, config=vars(args), name=run_name, monitor_gym=True, save_code=True, ) writer = SummaryWriter(f"runs/{run_name}") writer.add_text( "hyperparameters", "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])), ) # TRY NOT TO MODIFY: seeding random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.backends.cudnn.deterministic = args.torch_deterministic device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu") # env setup dino = "dino" in args.model_type envs = gym.vector.SyncVectorEnv( [ make_env( args.env_id, i, args.capture_video, run_name, mode=args.mode, dino=dino ) for i in range(args.num_envs) ], ) assert isinstance( envs.single_action_space, gym.spaces.Discrete ), "only discrete action space is supported" print(f"*** Model: {args.model_type} ***") if args.model_type == "cnn-simple": agent = CnnSimpleAgent(envs).to(device) elif args.model_type == "cnn-simple-ft": if len(args.prev_units) > 0: agent = CnnSimpleAgent.load( args.prev_units[0], envs, load_critic=False, reset_actor=True ).to(device) else: agent = CnnSimpleAgent(envs).to(device) elif args.model_type == "dino-simple": agent = DinoSimpleAgent( envs, dino_size=args.dino_size, frame_stack=4, device=device ).to(device) elif args.model_type == "cnn-componet": agent = CnnCompoNetAgent( envs, prevs_paths=args.prev_units, finetune_encoder=args.componet_finetune_encoder, map_location=device, ).to(device) elif args.model_type == "prog-net": agent = ProgressiveNetAgent( envs, prevs_paths=args.prev_units, map_location=device ).to(device) elif args.model_type == "packnet": # retraining in 20% of the total timesteps packnet_retrain_start = args.total_timesteps - int(args.total_timesteps * 0.2) if args.total_task_num is None: print("CLI argument `total_task_num` is required when using PackNet.") quit(1) if len(args.prev_units) == 0: agent = PackNetAgent( envs, task_id=(args.mode + 1), is_first_task=True, total_task_num=args.total_task_num, ).to(device) else: agent = PackNetAgent.load( args.prev_units[0], task_id=args.mode + 1, restart_actor_critic=True, freeze_bias=True, ).to(device) else: print(f"Model type {args.model_type} is not valid.") quit(1) optimizer = optim.Adam(agent.parameters(), lr=args.learning_rate, eps=1e-5) # ALGO Logic: Storage setup obs = torch.zeros( (args.num_steps, args.num_envs) + envs.single_observation_space.shape ).to(device) actions = torch.zeros( (args.num_steps, args.num_envs) + envs.single_action_space.shape ).to(device) logprobs = torch.zeros((args.num_steps, args.num_envs)).to(device) rewards = torch.zeros((args.num_steps, args.num_envs)).to(device) dones = torch.zeros((args.num_steps, args.num_envs)).to(device) values = torch.zeros((args.num_steps, args.num_envs)).to(device) # TRY NOT TO MODIFY: start the game global_step = 0 start_time = time.time() next_obs, _ = envs.reset(seed=args.seed) next_obs = torch.Tensor(next_obs).to(device) next_done = torch.zeros(args.num_envs).to(device) for iteration in range(1, args.num_iterations + 1): # Annealing the rate if instructed to do so. if args.anneal_lr: frac = 1.0 - (iteration - 1.0) / args.num_iterations lrnow = frac * args.learning_rate optimizer.param_groups[0]["lr"] = lrnow for step in range(0, args.num_steps): global_step += args.num_envs obs[step] = next_obs dones[step] = next_done # ALGO LOGIC: action logic with torch.no_grad(): if ( args.track and args.model_type == "cnn-componet" and global_step % 100 == 0 ): action, logprob, _, value = agent.get_action_and_value( next_obs / 255.0, log_writter=writer, global_step=global_step, prevs_to_noise=args.prevs_to_noise, ) elif args.model_type == "cnn-componet": action, logprob, _, value = agent.get_action_and_value( next_obs / 255.0, prevs_to_noise=args.prevs_to_noise ) else: action, logprob, _, value = agent.get_action_and_value( next_obs / 255.0 ) values[step] = value.flatten() actions[step] = action logprobs[step] = logprob # TRY NOT TO MODIFY: execute the game and log data. next_obs, reward, terminations, truncations, infos = envs.step( action.cpu().numpy() ) next_done = np.logical_or(terminations, truncations) rewards[step] = torch.tensor(reward).to(device).view(-1) next_obs, next_done = torch.Tensor(next_obs).to(device), torch.Tensor( next_done ).to(device) if "final_info" in infos: for info in infos["final_info"]: if info and "episode" in info: print( f"global_step={global_step}, episodic_return={info['episode']['r']}" ) writer.add_scalar( "charts/episodic_return", info["episode"]["r"], global_step ) writer.add_scalar( "charts/episodic_length", info["episode"]["l"], global_step ) # bootstrap value if not done with torch.no_grad(): next_value = agent.get_value(next_obs / 255.0).reshape(1, -1) advantages = torch.zeros_like(rewards).to(device) lastgaelam = 0 for t in reversed(range(args.num_steps)): if t == args.num_steps - 1: nextnonterminal = 1.0 - next_done nextvalues = next_value else: nextnonterminal = 1.0 - dones[t + 1] nextvalues = values[t + 1] delta = ( rewards[t] + args.gamma * nextvalues * nextnonterminal - values[t] ) advantages[t] = lastgaelam = ( delta + args.gamma * args.gae_lambda * nextnonterminal * lastgaelam ) returns = advantages + values # flatten the batch b_obs = obs.reshape((-1,) + envs.single_observation_space.shape) b_logprobs = logprobs.reshape(-1) b_actions = actions.reshape((-1,) + envs.single_action_space.shape) b_advantages = advantages.reshape(-1) b_returns = returns.reshape(-1) b_values = values.reshape(-1) # Optimizing the policy and value network b_inds = np.arange(args.batch_size) clipfracs = [] for epoch in range(args.update_epochs): np.random.shuffle(b_inds) for start in range(0, args.batch_size, args.minibatch_size): end = start + args.minibatch_size mb_inds = b_inds[start:end] if args.model_type == "cnn-componet": _, newlogprob, entropy, newvalue = agent.get_action_and_value( b_obs[mb_inds] / 255.0, b_actions.long()[mb_inds], prevs_to_noise=args.prevs_to_noise, ) else: _, newlogprob, entropy, newvalue = agent.get_action_and_value( b_obs[mb_inds] / 255.0, b_actions.long()[mb_inds] ) logratio = newlogprob - b_logprobs[mb_inds] ratio = logratio.exp() with torch.no_grad(): # calculate approx_kl http://joschu.net/blog/kl-approx.html old_approx_kl = (-logratio).mean() approx_kl = ((ratio - 1) - logratio).mean() clipfracs += [ ((ratio - 1.0).abs() > args.clip_coef).float().mean().item() ] mb_advantages = b_advantages[mb_inds] if args.norm_adv: mb_advantages = (mb_advantages - mb_advantages.mean()) / ( mb_advantages.std() + 1e-8 ) # Policy loss pg_loss1 = -mb_advantages * ratio pg_loss2 = -mb_advantages * torch.clamp( ratio, 1 - args.clip_coef, 1 + args.clip_coef ) pg_loss = torch.max(pg_loss1, pg_loss2).mean() # Value loss newvalue = newvalue.view(-1) if args.clip_vloss: v_loss_unclipped = (newvalue - b_returns[mb_inds]) ** 2 v_clipped = b_values[mb_inds] + torch.clamp( newvalue - b_values[mb_inds], -args.clip_coef, args.clip_coef, ) v_loss_clipped = (v_clipped - b_returns[mb_inds]) ** 2 v_loss_max = torch.max(v_loss_unclipped, v_loss_clipped) v_loss = 0.5 * v_loss_max.mean() else: v_loss = 0.5 * ((newvalue - b_returns[mb_inds]) ** 2).mean() entropy_loss = entropy.mean() loss = pg_loss - args.ent_coef * entropy_loss + v_loss * args.vf_coef optimizer.zero_grad() loss.backward() nn.utils.clip_grad_norm_(agent.parameters(), args.max_grad_norm) if args.model_type == "packnet": if global_step >= packnet_retrain_start: agent.start_retraining() # can be called multiple times, only the first counts agent.before_update() optimizer.step() if args.target_kl is not None and approx_kl > args.target_kl: break y_pred, y_true = b_values.cpu().numpy(), b_returns.cpu().numpy() var_y = np.var(y_true) explained_var = np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y # TRY NOT TO MODIFY: record rewards for plotting purposes writer.add_scalar( "charts/learning_rate", optimizer.param_groups[0]["lr"], global_step ) writer.add_scalar("losses/value_loss", v_loss.item(), global_step) writer.add_scalar("losses/policy_loss", pg_loss.item(), global_step) writer.add_scalar("losses/entropy", entropy_loss.item(), global_step) writer.add_scalar("losses/old_approx_kl", old_approx_kl.item(), global_step) writer.add_scalar("losses/approx_kl", approx_kl.item(), global_step) writer.add_scalar("losses/clipfrac", np.mean(clipfracs), global_step) writer.add_scalar("losses/explained_variance", explained_var, global_step) print("SPS:", int(global_step / (time.time() - start_time))) writer.add_scalar( "charts/SPS", int(global_step / (time.time() - start_time)), global_step ) envs.close() writer.close() if args.save_dir is not None: print(f"Saving trained agent in `{args.save_dir}` with name `{run_name}`") agent.save(dirname=f"{args.save_dir}/{run_name}")
18,170
Python
.py
417
32.611511
125
0.569379
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,732
process_results.py
mikelma_componet/experiments/atari/process_results.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D import pathlib import argparse from tabulate import tabulate import sys, os sys.path.append("../../") from utils import style SETTINGS = { "SpaceInvaders": dict( ma_w_1=10, num_pts_sc=100, sc_percent=1.0, chunk_avg_w=30, ma_w_extra=30, ma_std_extra=10, ), "Freeway": dict( ma_w_1=10, num_pts_sc=100, sc_percent=1.0, chunk_avg_w=30, ma_w_extra=10, ma_std_extra=None, ), } METHOD_NAMES = { "cnn-simple": "Baseline", "cnn-simple-ft": "FT", "cnn-componet": "CompoNet", "prog-net": "ProgressiveNet", "packnet": "PackNet", } METHOD_COLORS = { "cnn-simple": "darkgray", "cnn-simple-ft": "tab:orange", "cnn-componet": "tab:blue", "prog-net": "tab:green", "packnet": "tab:purple", } METHOD_ORDER = ["cnn-simple", "cnn-componet", "cnn-simple-ft", "prog-net", "packnet"] def parse_args(): # fmt: off parser = argparse.ArgumentParser() parser.add_argument("--data-dir", type=str, default="data/envs/Freeway", choices=["data/envs/Freeway", "data/envs/SpaceInvaders"], help="path to the directory where the CSV of each task is stored") parser.add_argument("--eval-results", type=str, default="data/eval_results.csv", help="path to the file where the CSV with the evaluation results is located") # fmt: on return parser.parse_args() def remove_nan(x, y): no_nan = ~np.isnan(y) return x[no_nan], y[no_nan] def moving_average(x, w): return np.convolve(x, np.ones(w), "valid") / w def chunk_average(x, w): split = np.array_split(x, x.shape[0] // w) x_avg = np.array([chunk.mean() for chunk in split]) x_std = np.array([chunk.std() for chunk in split]) return x_avg, x_std def compute_success( df, ma_w_1=10, num_pts_sc=100, sc_percent=0.8, chunk_avg_w=30, ma_w_extra=30, ma_std_extra=10, ): """Takes the DataFrame of the CSV file form W&B and returns a new dataframe with the success of each algorithm in every timestep. df -- DataFrame to process. ma_w_1 -- Window size of the moving average applied to the return curves before computing the success score. num_pts_sc -- Number of points to use to compute the success score. sc_percent -- Percentage of the average final return to take as the success score. chunk_avg_w -- Window size of the chunk average smoothing applied to the success curves. ma_w_extra -- Window size of the MA smoothing applied to the success curves. ma_std_extra -- Window size of the extra MA applied to the std of the success curves. """ data_cols = df.columns[df.columns.str.endswith("episodic_return")] # get the name of the method from the column's name methods = [col.split(" ")[1] for col in data_cols] # compute the success_score automatically as # the `sc_percent` % of the average return of # the last 100 episodes of all algorithms in # the dataframe rets = [] returns = {} for method, col in zip(methods, data_cols): x, y = df["global_step"].values, df[col].values x, y = remove_nan(x, y) x = moving_average(x, w=ma_w_1) y = moving_average(y, w=ma_w_1) returns[method] = (x, y) rets.append(y[:-num_pts_sc].mean()) success_score = sc_percent * np.mean(rets) data = {} for method in methods: x, y = returns[method] y = y >= success_score x, _ = chunk_average(x, w=chunk_avg_w) y, y_std = chunk_average(y, w=chunk_avg_w) if ma_w_extra is not None: x = moving_average(x, w=ma_w_extra) y = moving_average(y, w=ma_w_extra) y_std = moving_average(y_std, w=ma_w_extra) if ma_std_extra is not None: x_std = moving_average(x, w=10) y_min = moving_average(np.maximum(y - y_std, 0), w=10) y_max = moving_average(np.minimum(y + y_std, 1), w=10) else: x_std = x y_min = np.maximum(y - y_std, 0) y_max = np.minimum(y + y_std, 1) x = np.insert(x, 0, 0.0) y = np.insert(y, 0, 0.0) y_std = np.insert(y_std, 0, 0.0) y_min = np.insert(y_min, 0, 0.0) y_max = np.insert(y_max, 0, 0.0) x_std = np.insert(x_std, 0, 0.0) # plt.plot(x, y, label=method) # plt.fill_between( # x_std, # y_min, # y_max, # alpha=0.3 # ) d = {} d["global_step"] = x d["success"] = y d["std_high"] = y_max d["std_low"] = y_min d["std_x"] = x_std d["final_success"] = np.mean(y[-100:]) d["final_success_std"] = np.std(y[-100:]) data[method] = d # plt.gca() # plt.legend() # plt.show() return data, success_score def compute_forward_transfer(data): baseline_method = "cnn-simple" methods = list(METHOD_NAMES.keys()) ft_data = {} for task_id in data.keys(): ft_data[task_id] = {} # get the baseline's data task_data = data[task_id] x_baseline = task_data[baseline_method]["global_step"] y_baseline = task_data[baseline_method]["success"] baseline_area_down = np.trapz(x=x_baseline, y=y_baseline) baseline_area_up = np.max(x_baseline) - baseline_area_down for method in methods: x_method = task_data[method]["global_step"] y_method = task_data[method]["success"] y_baseline = task_data[baseline_method]["success"] # get a common X axis x = [] mi, bi = 0, 0 while mi < len(x_method) and bi < len(x_baseline): if x_method[mi] < x_baseline[bi]: x.append(x_method[mi]) mi += 1 else: x.append(x_baseline[bi]) bi += 1 x = np.array(x) y_baseline = np.interp(x, x_baseline, y_baseline) y_method = np.interp(x, x_method, y_method) # compute the actual FT up_idx = y_method > y_baseline down_idx = y_method < y_baseline area_up = np.trapz(y=y_method[up_idx], x=x[up_idx]) - np.trapz( y=y_baseline[up_idx], x=x[up_idx] ) area_down = np.trapz(y=y_baseline[down_idx], x=x[down_idx]) - np.trapz( y=y_method[down_idx], x=x[down_idx] ) ft = (area_up - area_down) / baseline_area_up ft_data[task_id][method] = ft # # Printing the results in a pretty table # methods = list(METHOD_NAMES.keys()) table = [] for task_id in sorted(ft_data.keys()): row = [task_id] for i, method in enumerate(methods): val = round(ft_data[task_id][method], 2) row.append(val) table.append(row) table.append([None] * len(method)) # compute the average and std FT of every method avgs = [] for method in methods: method_avg = [] for task_id in sorted(ft_data.keys())[ 1: ]: # ignore the first task to compute the avg. ft method_avg.append(ft_data[task_id][method]) mean = round(np.mean(method_avg), 2) std = round(np.std(method_avg), 2) avgs.append(f"{mean} ({std})") table.append(["Avg."] + avgs) print("\n\n----- FORWARD TRANSFER -----\n") print( tabulate( table, headers=["Task ID"] + [METHOD_NAMES[m] for m in methods], tablefmt="rounded_outline", ) ) return ft_data def compute_final_performance(data): methods = list(METHOD_NAMES.keys()) table = [] for task_id in sorted(data.keys()): row = [task_id] for i, method in enumerate(methods): val = round(data[task_id][method]["final_success"], 2) row.append(val) table.append(row) table.append([None] * len(method)) avgs = [] for j in range(1, len(table[0])): # skip task id's column m = [] for i in range(len(table) - 1): # skip Nones row m.append(table[i][j]) mean = round(np.mean(m), 2) std = round(np.std(m), 2) avgs.append(f"{mean} ({std})") table.append(["Avg."] + avgs) print("\n\n----- PERFORMANCE -----\n") print( tabulate( table, headers=["Task ID"] + [METHOD_NAMES[m] for m in methods], tablefmt="rounded_outline", ) ) print( "* NOTE: This is not the final performance in the case of the Finetune method, \nbut the performance at the time of solving each task.\n" ) def process_eval(df, data, success_scores, env): eval_results = {} for method in df["algorithm"].unique(): print( f"\n** Final performance of the \x1b[31;1m{METHOD_NAMES[method]}\x1b[0m method:" ) # per_task = {} perf_total = [] forg_total = [] perf_by_task = [] forg_by_task = [] for task_id in sorted(success_scores.keys()): sel = df[ (df["test mode"] == task_id) & (df["environment"] == env) & (df["algorithm"] == method) ] s = sel["ep ret"].values >= success_scores[task_id] # the performance when the current task was task_id past_perf = data[task_id]["cnn-simple-ft"]["final_success"] perf_total += list(s) forg_total += list(past_perf - s) perf = round(s.mean(), 2) perf_std = round(s.std(), 2) forg = round((past_perf - s).mean(), 2) forg_std = round((past_perf - s).std(), 2) print( f" - Task {task_id} => Perf.: {perf} [{perf_std}], Forg.: {forg} [{forg_std}]" ) perf_by_task.append((perf, perf_std)) forg_by_task.append((forg, forg_std)) perf = round(np.mean(perf_total), 2) perf_std = round(np.std(perf_total), 2) forg = round(np.mean(forg_total), 2) forg_std = round(np.std(forg_total), 2) print(f" + Avg: Perf.: {perf} [{perf_std}], Forg.: {forg} [{forg_std}]") eval_results[method] = {} eval_results[method]["perf"] = perf_by_task eval_results[method]["forg"] = forg_by_task return eval_results def plot_data(data, save_name="plot.pdf", total_timesteps=1e6): methods = METHOD_ORDER num_tasks = len(data.keys()) fig, axes = plt.subplots(nrows=len(methods) + 1, figsize=(10, 8)) # # Plot all the method together # ax = axes[0] for i in range(num_tasks): for method in methods: offset = i * total_timesteps ax.plot( data[i][method]["global_step"] + offset, data[i][method]["success"], c=METHOD_COLORS[method], linewidth=0.8, ) ax.set_ylabel("Success") ax.set_xticks( np.arange(num_tasks) * 1e6, [f"{i}" for i in range(num_tasks)], fontsize=7, color="dimgray", ) ax.vlines( x=np.arange(num_tasks) * 1e6, ymin=0.0, ymax=1, colors="tab:gray", alpha=0.3, linestyles="dashed", linewidths=0.7, ) style(fig, ax=ax, legend=False, grid=False, ax_math_ticklabels=False) for i, method in enumerate(METHOD_ORDER): color = METHOD_COLORS[METHOD_ORDER[i]] ax = axes[i + 1] ax.vlines( x=np.arange(num_tasks) * 1e6, ymin=0.0, ymax=1, colors="tab:gray", alpha=0.3, linestyles="dashed", linewidths=0.7, ) ax.set_xticks( np.arange(num_tasks) * 1e6, [f"{i}" for i in range(num_tasks)], fontsize=7, color="dimgray", ) ax.set_ylabel(f"{METHOD_NAMES[method]}\n\nSuccess") for task_id in range(num_tasks): x = data[task_id][method]["global_step"] y = data[task_id][method]["success"] y_high = data[task_id][method]["std_high"] y_low = data[task_id][method]["std_low"] x_std = data[task_id][method]["std_x"] offset = task_id * total_timesteps ax.plot(x + offset, y, c=color, linewidth=0.8) ax.fill_between( x_std + offset, y_low, y_high, alpha=0.3, color=color, ) style(fig, ax=ax, legend=False, grid=False, ax_math_ticklabels=False) # only applied to the last `ax` (plot) ax.set_xlabel("Task ID") lines = [ Line2D([0], [0], color=METHOD_COLORS[METHOD_ORDER[i]]) for i in range(len(methods)) ] fig.legend( lines, [METHOD_NAMES[m] for m in METHOD_ORDER], fancybox=False, frameon=False, loc="outside lower center", ncols=len(methods), ) plt.savefig(save_name, pad_inches=0, bbox_inches="tight") plt.show() if __name__ == "__main__": args = parse_args() env = os.path.basename(args.data_dir) # # Compute the success curve of each method in every task # data = {} scores = {} for path in pathlib.Path(args.data_dir).glob("*.csv"): task_id = int(str(path)[:-4].split("_")[-1]) # obtain task ID from the path df = pd.read_csv(path) cfg = dict() for k in SETTINGS.keys(): if k in str(path): cfg = SETTINGS[k] break data_task, success_score = compute_success(df, **cfg) data[task_id] = data_task scores[task_id] = success_score print("\n** Success scores used:") [print(round(scores[t], 2), end=" ") for t in sorted(scores.keys())] print() # # Compute forward transfer & final performance # if os.path.exists(args.eval_results): eval_results = process_eval( pd.read_csv(args.eval_results), data, scores, f"ALE/{env}-v5" ) else: eval_results = None ft_data = compute_forward_transfer(data) compute_final_performance(data) fname = f"summary_data_{env}.csv" with open(fname, "w") as f: f.write("env,method,task id,perf,perf std,ft,forg,forg std\n") for task_id in sorted(list(data.keys())): for method in data[0].keys(): ft = ft_data[task_id][method] if eval_results is not None and method in eval_results.keys(): perf, perf_std = eval_results[method]["perf"][task_id] forg, forg_std = eval_results[method]["forg"][task_id] if METHOD_NAMES[method] == "Finetune": n_perf = data[task_id][method]["final_success"] n_perf_std = data[task_id][method]["final_success_std"] f.write( f"{env},Finetune-N,{task_id},{n_perf},{n_perf_std},{ft},0,0\n" ) else: perf = data[task_id][method]["final_success"] perf_std = data[task_id][method]["final_success_std"] forg, forg_std = 0, 0 f.write( f"{env},{METHOD_NAMES[method]},{task_id},{perf},{perf_std},{ft},{forg},{forg_std}\n" ) print(f"\n*** A summary of the results has been saved to `{fname}` ***\n") # # Plotting # env = args.data_dir.split("/")[-1] plot_data(data, save_name=f"success_curves_{env}.pdf")
16,018
Python
.py
437
27.434783
145
0.541083
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,733
plot_arch_val.py
mikelma_componet/experiments/atari/plot_arch_val.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from argparse import ArgumentParser import sys, os sys.path.append("../../") from utils import plt_style def parse_args(): # fmt: off parser = ArgumentParser() parser.add_argument("--dir-prefix", type=str, default="data/arch-val", help="directory where the CSV data of the architectural validation experiments is stored") # fmt: on return parser.parse_args() def smooth_curve(df, data_col, idx_col="global_step", chunksize=None, w=None): idx = ~df[data_col].isnull() y = df[data_col][idx].values x = df[idx_col][idx].values # compute the average of chunks if chunksize is not None: n = x.shape[0] x = np.array([c.mean() for c in np.array_split(x, n // chunksize)]) y = np.array([c.mean() for c in np.array_split(y, n // chunksize)]) # second smotthing with a moving average if w is not None: x = np.convolve(x, np.ones(w), "valid") / w y = np.convolve(y, np.ones(w), "valid") / w return x, y def plot_ep_ret(fig, ax, path="data/ep_ret.csv", save_prefix="", legend_loc="best", figlabel="(i)"): df = pd.read_csv(path) cols = df.columns col_method = cols[ cols.str.contains("cnn-componet") & cols.str.endswith("episodic_return") ][0] col_ref = cols[ cols.str.contains("cnn-simple") & cols.str.endswith("episodic_return") ][0] x, y_ref = smooth_curve(df, data_col=col_ref, chunksize=100, w=10) x_min, y_min = smooth_curve(df, data_col=col_ref + "__MIN", chunksize=100, w=10) x_max, y_max = smooth_curve(df, data_col=col_ref + "__MAX", chunksize=100, w=10) ax.plot(x, y_ref, label="Baseline") ax.fill_between(x, y_min, y_max, alpha=0.2) x, y_method = smooth_curve(df, data_col=col_method, chunksize=100, w=10) x_min, y_min = smooth_curve(df, data_col=col_method + "__MIN", chunksize=100, w=10) x_max, y_max = smooth_curve(df, data_col=col_method + "__MAX", chunksize=100, w=10) ax.plot( x, y_method, label="CompoNet", marker="X", markersize=10, markeredgecolor="white", markevery=len(x) // 5, ) ax.fill_between(x, y_min, y_max, alpha=0.2) ax.set_xlabel(f"Timestep\n{figlabel}") ax.set_ylabel("Episodic return") # place a text box in upper left in axes coords # props = dict(boxstyle="round", facecolor="wheat", alpha=0.5) # ax.text( # 0.02, # 0.97, # figlabel, # transform=ax.transAxes, # fontsize=14, # verticalalignment="top", # bbox=props, # ) plt_style.style(fig, ax, legend=False) ax.legend(fancybox=False, frameon=False, loc=legend_loc) def plot_matches(fig, ax, path="data/matches.csv", save_prefix="", figlabel="(ii)"): df = pd.read_csv(path) cols = df.columns col_out_m_head_out = cols[cols.str.endswith("out_matches_head_out")][0] col_out_m_int_pol = cols[cols.str.endswith("out_matches_int_pol")][0] col_int_pol_m_head = cols[cols.str.endswith("int_pol_matches_head")][0] cols = [col_out_m_head_out, col_out_m_int_pol, col_int_pol_m_head] # labels = ["out = out-head", "out = int-pol", "out-head = int-pol"] labels = ["Out = Out head", "Out = Int. pol.", "Out head = Int. pol."] markers = [None, "D", "o"] for i, (col, lbl) in enumerate(zip(cols, labels)): x, y = smooth_curve(df, data_col=col, chunksize=10, w=None) x_min, y_min = smooth_curve(df, data_col=col + "__MIN", chunksize=10, w=3) _, y_max = smooth_curve(df, data_col=col + "__MAX", chunksize=10, w=3) select = x <= (1e6 / 3) std_select = x_min <= (1e6 / 3) ax.plot( x[select], y[select], label=lbl, marker=markers[i], markersize=8, markeredgecolor="white", markevery=len(x[select]) // 5, ) ax.fill_between( x_min[std_select], y_min[std_select], y_max[std_select], alpha=0.2 ) ax.set_xlabel(f"Timestep\n{figlabel}") ax.set_ylabel("Matching rate") plt_style.style(fig, ax, legend=False, force_sci_x=True) ax.legend(fancybox=False, frameon=False) # props = dict(boxstyle="round", facecolor="wheat", alpha=0.5) # ax.text( # 0.02, # 0.97, # figlabel, # transform=ax.transAxes, # fontsize=14, # verticalalignment="top", # bbox=props, # ) def plot_attention( fif, ax, path=None, is_input=True, save_prefix="", mark_last=True, legend_cols=1, legend_loc=None, figlabel="(iii)" ): if path is None: path = "data/input_attentions.csv" if is_input else "data/output_attentions.csv" df = pd.read_csv(path) cols = df.columns num_atts = len(cols[cols.str.contains("att_") & ~cols.str.contains("__")]) for i in range(num_atts): col = cols[cols.str.endswith(f"att_{'in' if is_input else 'out'}_{i}")][0] x, y = smooth_curve(df, data_col=col, chunksize=10, w=None) x_std, y_min = smooth_curve(df, data_col=col + "__MIN", chunksize=20, w=10) _, y_max = smooth_curve(df, data_col=col + "__MAX", chunksize=20, w=10) if is_input: lbl = f"Prev. {i}" if i < num_atts - 1 else "Out head" else: lbl = f"Prev. {i}" if i == 4 and mark_last: kwargs = dict( marker="^", markersize=10, markeredgecolor="white", markevery=len(x) // 5, ) lbl = "Inf. Mod." elif lbl == "Out head": kwargs = dict( marker="o", markersize=8, markeredgecolor="white", markevery=len(x) // 5, ) else: kwargs = dict() ax.plot(x, y, label=lbl, **kwargs) ax.fill_between(x_std, y_min, y_max, alpha=0.2) ax.set_ylim(0, 1.1) ax.set_xlabel(f"Timestep\n{figlabel}") l = "In." if is_input else "Out" ax.set_ylabel(f"{l} head's attention val.") plt_style.style(fig, ax, legend=False) if legend_loc is None: legend_loc = "upper right" if is_input else "best" ax.legend(fancybox=False, frameon=False, loc=legend_loc, ncols=legend_cols) # props = dict(boxstyle="round", facecolor="wheat", alpha=0.5) # ax.text( # 0.05, # 0.95, # figlabel, # transform=ax.transAxes, # fontsize=14, # verticalalignment="top", # bbox=props, # ) if __name__ == "__main__": args = parse_args() for i, dirname in enumerate( [ f"{args.dir_prefix}/data_all_prevs_to_noise", f"{args.dir_prefix}/data_noise_except_task4", ] ): plt.rcParams.update({"font.size": 12, "axes.labelsize": 13.5}) fig, axs = plt.subplots(ncols=2, nrows=2, figsize=(8, 6)) plot_ep_ret( fig, axs[0, 0], path=f"{dirname}/ep_ret.csv", save_prefix=dirname + "_", legend_loc="best" if i == 1 else "lower right", figlabel="(a)" if i == 1 else "(e)" ) plot_matches( fig, axs[0, 1], path=f"{dirname}/matches.csv", save_prefix=dirname + "_", figlabel="(b)" if i == 1 else "(f)" ) plot_attention( fig, axs[1, 0], path=f"{dirname}/input_attentions.csv", is_input=True, save_prefix=dirname + "_", mark_last=i == 1, legend_cols=2 if i == 1 else 1, legend_loc="center right" if i == 1 else "best", figlabel="(c)" if i == 1 else "(g)", ) plot_attention( fig, axs[1, 1], path=f"{dirname}/output_attentions.csv", is_input=False, save_prefix=dirname + "_", mark_last=i == 1, figlabel="(d)" if i == 1 else "(h)" ) plt.tight_layout() plt.savefig(f"{os.path.basename(dirname)}.pdf", pad_inches=0, bbox_inches="tight") plt.show()
8,232
Python
.py
221
29.357466
100
0.555695
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,734
task_utils.py
mikelma_componet/experiments/atari/task_utils.py
TASKS = { "ALE/SpaceInvaders-v5": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], "ALE/Freeway-v5": [0, 1, 2, 3, 4, 5, 6, 7], } def parse_name_info(name): fields = name.split("__") if "SpaceInvaders" in fields[0]: env = "ALE/SpaceInvaders-v5" elif "Freeway" in fields[0]: env = "ALE/Freeway-v5" mode = int(fields[0].split("_")[-1]) algorithm = fields[1] seed = int(fields[3]) return env, mode, algorithm, seed def path_from_other_mode(base_path, new_mode): sep_idx = base_path.index("_") double_sep_idx = base_path.index("__") new_path = base_path[: sep_idx + 1] + str(new_mode) + base_path[double_sep_idx:] return new_path
680
Python
.py
19
31
84
0.590563
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,735
transfer_matrix.py
mikelma_componet/experiments/atari/transfer_matrix.py
from tensorboard.backend.event_processing import event_accumulator import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import pathlib from tqdm import tqdm import numpy as np import sys, os from argparse import ArgumentParser def parse_args(): # fmt: off parser = ArgumentParser() parser.add_argument("--runs-dir", type=str, default="runs", help="directory where the TensorBoard logs are stored") parser.add_argument("--save-csv", type=str, default="data/data_transfer_matrix_raw.csv", help="directory where the TensorBoard logs are stored") # fmt: on return parser.parse_args() def parse_metadata(ea): md = ea.Tensors("hyperparameters/text_summary")[0] md_bytes = md.tensor_proto.SerializeToString() # remove first non-ascii characters and parse start = md_bytes.index(b"|") md_str = md_bytes[start:].decode("ascii") md = {} for row in md_str.split("\n")[2:]: s = row.split("|")[1:-1] k = s[0] if s[1].isdigit(): v = int(s[1]) elif s[1].replace(".", "").isdigit(): v = float(s[1]) elif s[1] == "True" or s[1] == "False": v = s[1] == "True" else: v = s[1] md[k] = v return md def parse_tensorboard(path, scalars, single_pts=[]): """returns a dictionary of pandas dataframes for each requested scalar""" ea = event_accumulator.EventAccumulator( path, size_guidance={event_accumulator.SCALARS: 0}, ) _absorb_print = ea.Reload() # make sure the scalars are in the event accumulator tags if sum([s not in ea.Tags()["scalars"] for s in scalars]) > 0: print(f"** Scalar not found. Skipping file {path}") return None md = parse_metadata(ea) for name in single_pts: if name in ea.Tags()["scalars"]: md[name] = pd.DataFrame(ea.Scalars(name))["value"][0] return {k: pd.DataFrame(ea.Scalars(k)) for k in scalars}, md def areas_up_down(method_x, method_y, baseline_x, baseline_y): up_idx = method_y > baseline_y down_idx = method_y < baseline_y assert ( method_x == baseline_x ).all(), "The X axis of the baseline and method must be equal." x = method_x area_up = np.trapz(y=method_y[up_idx], x=x[up_idx]) - np.trapz( y=baseline_y[up_idx], x=x[up_idx] ) area_down = np.trapz(y=baseline_y[down_idx], x=x[down_idx]) - np.trapz( y=method_y[down_idx], x=x[down_idx] ) return area_up, area_down def remove_nan(x, y): no_nan = ~np.isnan(y) return x[no_nan], y[no_nan] def moving_average(x, w): return np.convolve(x, np.ones(w), "valid") / w def chunk_average(x, w): split = np.array_split(x, x.shape[0] // w) x_avg = np.array([chunk.mean() for chunk in split]) x_std = np.array([chunk.std() for chunk in split]) return x_avg, x_std def compute_success(df, xkey, ykey, score, ma_w, chunk_w, ma_w_extra): g = df.groupby(xkey)[ykey] mean = g.mean() y = mean.values x = mean.reset_index()[xkey].values x = moving_average(x, w=ma_w) y = moving_average(y, w=ma_w) y = y >= score y, _ = chunk_average(y, chunk_w) x, _ = chunk_average(x, chunk_w) x = moving_average(x, w=ma_w) y = moving_average(y, w=ma_w) x = np.insert(x, 0, 0.0) y = np.insert(y, 0, 0.0) return remove_nan(x, y) def transfer_matrix(df, success_scores, ma_w=10, chunk_w=30, ma_w_extra=30): num_tasks = df["first task"].max() + 1 F = np.zeros((num_tasks, num_tasks)) for first_task in range(num_tasks): for second_task in range(num_tasks): # get the success score for this task score = float( success_scores[success_scores["task"] == second_task][ "success score" ].iloc[0] ) # baseline method trained in the second task baseline = df[ (df["model"] == "cnn-simple") & (df["first task"] == second_task) ] x_baseline, y_baseline = compute_success( baseline, xkey="step", ykey="value", score=score, ma_w=ma_w, chunk_w=chunk_w, ma_w_extra=ma_w_extra, ) baseline_area_down = np.trapz(y=y_baseline, x=x_baseline) baseline_area_up = np.max(x_baseline) - baseline_area_down # get the method's data method = df[ (df["model"] == "cnn-simple-ft") & (df["first task"] == first_task) & (df["second task"] == second_task) ] if len(method["seed"].unique()) != len(baseline["seed"].unique()): print(f"* Skipping, first={first_task}, second={second_task}") continue # episodic return to success x_method, y_method = compute_success( method, xkey="step", ykey="value", score=score, ma_w=ma_w, chunk_w=chunk_w, ma_w_extra=ma_w_extra, ) # # Compute forward transfer # # get a common X axis x = [] mi, bi = 0, 0 while mi < len(x_method) and bi < len(x_baseline): if x_method[mi] < x_baseline[bi]: x.append(x_method[mi]) mi += 1 else: x.append(x_baseline[bi]) bi += 1 x = np.array(x) y_b = np.interp(x, x_baseline, y_baseline) y_m = np.interp(x, x_method, y_method) # areas where the method's curve is above or below the baseline up_idx = y_m > y_b down_idx = y_m < y_b # compute the integrals area_up = np.trapz(y=y_m[up_idx], x=x[up_idx]) - np.trapz( y=y_b[up_idx], x=x[up_idx] ) area_down = np.trapz(y=y_b[down_idx], x=x[down_idx]) - np.trapz( y=y_m[down_idx], x=x[down_idx] ) ft = (area_up - area_down) / baseline_area_up F[first_task, second_task] = ft return F def reference_transfer(F): n = F.shape[0] s = [] for i in range(1, n): r = [] for j in range(i): r.append(F[j, i]) s.append(max(r)) return np.sum(s) / n if __name__ == "__main__": args = parse_args() scalar = "charts/episodic_return" # # Convert tensorboard's data to a useful CSV # if not os.path.exists(args.save_csv): dfs = [] for path in tqdm(list(pathlib.Path(args.runs_dir).rglob("*events.out*"))): res = parse_tensorboard(str(path), [scalar]) if res is not None: dic, md = res else: print("No data. Skipping...") continue first_task = md["mode"] seed = md["seed"] model_type = md["model_type"] env = md["env_id"] if model_type == "cnn-simple-ft": second_task = int(md["prev_units"][12:-4].split("_")[1]) else: second_task = None # print(seed, first_task, second_task) df = dic[scalar] df["first task"] = first_task df["second task"] = second_task df["seed"] = seed df["model"] = model_type df["env"] = env dfs.append(df) df = pd.concat(dfs) df.to_csv(args.save_csv, index=False) else: print(f"** Using the cache file in {args.save_csv}") df = pd.read_csv(args.save_csv) # default values used in these envs (see process_results.py) ma_w = 10 chunk_w = 30 ma_w_extra = 30 fs = 14 plt.rc("axes", labelsize=fs) # fontsize of the x and y labels plt.rc("xtick", labelsize=fs) # fontsize of the tick labels plt.rc("ytick", labelsize=fs) # fontsize of the tick labels for env in ["Freeway", "SpaceInvaders"]: success_scores = pd.read_csv(f"data/success_scores_{env}.csv") data = df[df["env"] == f"ALE/{env}-v5"] F = transfer_matrix(data, success_scores, ma_w, chunk_w, ma_w_extra) rt = reference_transfer(F) print("\n=> Reference transfer:", rt) print() F = np.round(F, 2) sns.heatmap(F, annot=True, cmap="RdYlGn", center=0.0, vmin=-1, vmax=1) plt.xlabel("Second task") plt.ylabel("First task") plt.savefig(f"transfer_matrix_{env}.pdf", pad_inches=0, bbox_inches="tight") plt.show()
8,793
Python
.py
233
28.154506
92
0.539529
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,736
test_agent.py
mikelma_componet/experiments/atari/test_agent.py
import gymnasium as gym import numpy as np import torch import argparse import os from stable_baselines3.common.atari_wrappers import ( # isort:skip ClipRewardEnv, EpisodicLifeEnv, FireResetEnv, MaxAndSkipEnv, NoopResetEnv, ) from models import ( CnnSimpleAgent, DinoSimpleAgent, CnnCompoNetAgent, ProgressiveNetAgent, PackNetAgent, ) from task_utils import parse_name_info, path_from_other_mode def parse_arguments(): parser = argparse.ArgumentParser() # fmt: off parser.add_argument("--load", type=str, required=True) parser.add_argument("--seed", type=int, default=None) parser.add_argument("--mode", type=int, default=None) parser.add_argument("--max-timesteps", type=int, default=1000) parser.add_argument("--num-episodes", type=int, default=10) parser.add_argument('--render', default=False, action='store_true') parser.add_argument('--csv', default=None, type=str) # fmt: on return parser.parse_args() def make_env(env_id, idx, run_name, render_mode=None, mode=None): def thunk(): env = gym.make(env_id, mode=mode, render_mode=render_mode) env = gym.wrappers.RecordEpisodeStatistics(env) # env = NoopResetEnv(env, noop_max=30) env = MaxAndSkipEnv(env, skip=4) # env = EpisodicLifeEnv(env) env = gym.wrappers.ResizeObservation(env, (84, 84)) env = gym.wrappers.GrayScaleObservation(env) env = gym.wrappers.FrameStack(env, 4) return env return thunk if __name__ == "__main__": args = parse_arguments() env_name, train_mode, algorithm, seed = parse_name_info(args.load.split("/")[-1]) mode = train_mode if args.mode is None else args.mode seed = seed if args.seed is None else args.seed print( f"\nEnvironment: {env_name}, train/test mode: {train_mode}/{mode}, algorithm: {algorithm}, seed: {seed}\n" ) # make the environment envs = gym.vector.SyncVectorEnv([make_env(env_name, 1, run_name="test", mode=mode)]) env_fn = make_env( env_name, 0, run_name="test", mode=mode, render_mode="human" if args.render else None, ) env = env_fn() # load the model device = "cuda" if torch.cuda.is_available() else "cpu" if algorithm in ["cnn-simple", "cnn-simple-ft"]: agent = CnnSimpleAgent.load( args.load, envs, load_critic=False, map_location=device ) elif algorithm == "cnn-componet": prevs_paths = [path_from_other_mode(args.load, i) for i in range(mode)] agent = CnnCompoNetAgent.load( args.load, envs, prevs_paths=prevs_paths, map_location=device ) elif algorithm == "packnet": task_id = None if args.mode == None else args.mode + 1 agent = PackNetAgent.load(args.load, task_id=task_id, map_location=device) agent.network.set_view(task_id) if mode != train_mode: # load the actor and critic heads from the model trained in the testing task (game mode) path = path_from_other_mode(args.load, mode) ac = PackNetAgent.load(path, map_location=device) agent.critic = ac.critic agent.actor = ac.actor else: print(f"Loading of agent type `{algorithm}` is not implemented.") quit(1) agent.to(device) # # Main loop # ~~~~~~~~~ ep_rets = [] for _ in range(args.num_episodes): observation, info = env.reset(seed=seed) ep_ret = 0 for _ in range(args.max_timesteps): observation = torch.from_numpy(np.array(observation)).to(device) / 255.0 observation = observation.unsqueeze(0) action, _, _, _ = agent.get_action_and_value(observation) observation, reward, terminated, truncated, info = env.step( action[0].item() ) ep_ret += reward if terminated or truncated: print(f"Episodic return: {ep_ret}") ep_rets.append(ep_ret) break print() print("Avg. episodic return:", np.mean(ep_rets)) if args.csv: exists = os.path.exists(args.csv) with open(args.csv, "w" if not exists else "a") as f: if not exists: f.write("algorithm,environment,train mode,test mode,seed,ep ret\n") for v in ep_rets: f.write(f"{algorithm},{env_name},{train_mode},{mode},{seed},{v}\n")
4,503
Python
.py
115
31.530435
114
0.626434
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,737
plot_ablation_output_head.py
mikelma_componet/experiments/atari/plot_ablation_output_head.py
import pandas as pd import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D from glob import glob from argparse import ArgumentParser import sys sys.path.append("../../") from utils import plt_style def parse_args(): # fmt: off parser = ArgumentParser() parser.add_argument("--dirname", type=str, default="data/output_head_ablation", help="directory where the CSV data of the experiments is stored") # fmt: on return parser.parse_args() def chunk_smoothing(series, chunksize): assert chunksize % 2 != 0, "process_data: chunksize must be odd" arr = series.values chunked = np.array_split(arr, arr.shape[0] // chunksize) avgs = [c.mean() for c in chunked] stds = [c.std() for c in chunked] return np.array(avgs), np.array(stds) def preprocess_data(df, data_col, idx_col, rw_winsize=100, chunksize=111, last_eps=100): non_null = ~df[data_col].isnull() df = df[non_null] # rolling window smoothing df.loc[:, data_col] = df[data_col].rolling(window=rw_winsize).mean() # smooth by averaging chunks chunks data, data_std = chunk_smoothing(df[data_col], chunksize=chunksize) idx, _ = chunk_smoothing(df[idx_col], chunksize=chunksize) return pd.DataFrame({ data_col: data, data_col+"_std": data_std, idx_col: idx, # "last avg": last_avg, "last std": last_std }) def dir_to_df(dirname, winsize=100, chunk_size=101): dfs = [] for i, path in enumerate(glob(f"{dirname}/*.csv")): task_id = int(path.split("/")[-1][5:-4]) if task_id == 0: continue df = pd.read_csv(path) data_col = df.columns[ df.columns.str.contains("cnn-componet") & df.columns.str.endswith("episodic_return") ][0] df = df[[data_col, "global_step"]] df = df.rename(columns={data_col: "ep_ret"}) df = preprocess_data( df, data_col="ep_ret", idx_col="global_step", rw_winsize=winsize, chunksize=chunk_size, ) df["task_id"] = task_id # df["global_step"] += i * total_timesteps dfs.append(df) return pd.concat(dfs) def single_file_to_df(path, winsize=100, chunk_size=101): df = pd.read_csv(path) ep_ret_cols = df.columns[df.columns.str.endswith("episodic_return")] dfs = [] for col in ep_ret_cols: task_id = int(col.split(" ")[1]) sel = df[[col, "global_step"]].copy() sel = df.rename(columns={col: "ep_ret"}) sel = preprocess_data( sel, data_col="ep_ret", idx_col="global_step", rw_winsize=winsize, chunksize=chunk_size, ) sel["task_id"] = task_id dfs.append(sel) df = pd.concat(dfs) return df def generate_plot(dir_prefix, env, winsize, chunk_size): lbls = ["Original", "Ablated"] colors = ["tab:blue", "tab:orange"] no_out_head = dir_to_df(f"{dir_prefix}/no_out_head/{env}", chunk_size=chunk_size, winsize=winsize) normal = dir_to_df(f"{dir_prefix}/with_out_head/{env}", chunk_size=chunk_size, winsize=winsize) dfs = [normal, no_out_head] tasks = sorted(normal["task_id"].unique()[1:]) fig, axes = plt.subplots(nrows=1, ncols=len(tasks), figsize=(20, 3.5)) for i, task_id in enumerate(tasks): ax = axes[i] plt_style.style(fig, ax=ax, legend=False) if i > 0: ax.set_xticks([]) else: ax.set_ylabel("Episodic return", fontsize=13) ax.set_xlabel("Timestep", fontsize=13) for data in dfs: sel = data[data["task_id"] == task_id] ax.plot(sel["global_step"], sel["ep_ret"], label="Yes") ax.fill_between( sel["global_step"], sel["ep_ret"] - sel["ep_ret_std"], sel["ep_ret"] + sel["ep_ret_std"], label="Yes", alpha=0.3, ) ax.tick_params(axis='y', labelsize=10) ax.tick_params(axis='x', labelsize=14) ax.set_title(f"Task {task_id}") # Shrink current axis's height by 10% on the bottom p = 0.2 # % box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * p, box.width, box.height * (1-p)]) custom_lines = [Line2D([0], [0], color=c) for c in colors] fig.legend(custom_lines, lbls, fancybox=False, frameon=False, loc="outside lower center", ncols=len(lbls), fontsize=14) plt.savefig(f"out_head_ablation_curves_{env}.pdf", pad_inches=0, bbox_inches='tight') plt.show() if __name__ == "__main__": args = parse_args() generate_plot(args.dirname, "SpaceInvaders", winsize=100, chunk_size=501) generate_plot(args.dirname, "Freeway", winsize=50, chunk_size=101)
4,871
Python
.py
120
32.683333
102
0.594955
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,738
run_experiments.py
mikelma_componet/experiments/atari/run_experiments.py
import subprocess import argparse import random from task_utils import TASKS def parse_args(): # fmt: off parser = argparse.ArgumentParser() parser.add_argument("--algorithm", type=str, choices=["componet", "finetune", "from-scratch", "prog-net", "packnet"], required=True) parser.add_argument("--env", type=str, choices=["ALE/SpaceInvaders-v5", "ALE/Freeway-v5"], default="ALE/SpaceInvaders-v5") parser.add_argument("--seed", type=int, required=False, default=None) parser.add_argument("--start-mode", type=int, required=True) parser.add_argument("--first-mode", type=int, required=True) parser.add_argument("--last-mode", type=int, required=True) # fmt: on return parser.parse_args() args = parse_args() modes = TASKS[args.env] start_mode = args.start_mode if args.algorithm == "finetune": model_type = "cnn-simple-ft" elif args.algorithm == "componet": model_type = "cnn-componet" elif args.algorithm == "from-scratch": model_type = "cnn-simple" elif args.algorithm == "prog-net": model_type = "prog-net" elif args.algorithm == "packnet": model_type = "packnet" seed = random.randint(0, 1e6) if args.seed is None else args.seed run_name = ( lambda task_id: f"{args.env.replace('/', '-')}_{task_id}__{model_type}__run_ppo__{seed}" ) timesteps = int(1e6) first_idx = modes.index(start_mode) for i, task_id in enumerate(modes[first_idx:]): params = f"--track --model-type={model_type} --env-id={args.env} --seed={seed}" params += f" --mode={task_id} --save-dir=agents --total-timesteps={timesteps}" # algorithm specific CLI arguments if args.algorithm == "componet": params += " --componet-finetune-encoder" if args.algorithm == "packnet": params += f" --total-task-num={len(modes)}" if first_idx > 0 or i > 0: # multiple previous modules if args.algorithm in ["componet", "prog-net"]: params += " --prev-units" for i in modes[: modes.index(task_id)]: params += f" agents/{run_name(i)}" # single previous module elif args.algorithm in ["finetune", "packnet"]: params += f" --prev-units agents/{run_name(task_id-1)}" # Launch experiment cmd = f"python3 run_ppo.py {params}" print(cmd) res = subprocess.run(cmd.split(" ")) if res.returncode != 0: print(f"*** Process returned code {res.returncode}. Stopping on error.") quit(1)
2,464
Python
.py
58
37.37931
136
0.651756
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,739
progressive_net.py
mikelma_componet/experiments/atari/models/progressive_net.py
import torch import torch.nn as nn from torch.distributions.categorical import Categorical import numpy as np import os def layer_init(layer, std=np.sqrt(2), bias_const=0.0): torch.nn.init.orthogonal_(layer.weight, std) if layer.bias is not None: torch.nn.init.constant_(layer.bias, bias_const) return layer class ProgressiveNetAgent(nn.Module): def __init__(self, envs, prevs_paths=[], map_location=None): super().__init__() hidden_dim = 512 prevs = [ torch.load(f"{p}/encoder.pt", map_location=map_location) for p in prevs_paths ] self.encoder = ProgressiveNet( hidden_dim=hidden_dim, out_dim=hidden_dim, previous_models=prevs, layer_init=layer_init, ) self.actor = layer_init( nn.Linear(hidden_dim, envs.single_action_space.n), std=0.01 ) self.critic = layer_init(nn.Linear(hidden_dim, 1), std=1) def get_value(self, x): hidden = self.encoder(x) return self.critic(hidden) def get_action_and_value(self, x, action=None): hidden = self.encoder(x) logits = self.actor(hidden) probs = Categorical(logits=logits) if action is None: action = probs.sample() return action, probs.log_prob(action), probs.entropy(), self.critic(hidden) def save(self, dirname): os.makedirs(dirname, exist_ok=True) if hasattr(self.encoder, "previous_models"): del self.encoder.previous_models torch.save(self.actor, f"{dirname}/actor.pt") torch.save(self.encoder, f"{dirname}/encoder.pt") torch.save(self.critic, f"{dirname}/crititc.pt") def load(dirname, envs, prevs_paths, map_location=None): model = ProgressiveNetAgent(envs=envs, prevs_paths=prevs_paths) model.actor = torch.load(f"{dirname}/actor.pt", map_location=map_location) model.encoder = torch.load(f"{dirname}/encoder.pt", map_location=map_location) model.critic = torch.load(f"{dirname}/critic.pt", map_location=map_location) return model class ProgressiveNet(nn.Module): def __init__( self, hidden_dim, out_dim, previous_models=[], layer_init=lambda x, **kwargs: x ): super().__init__() n_prev = len(previous_models) self.n_prev = n_prev self.c1 = layer_init(nn.Conv2d(4, 32, 8, stride=4)) self.c2 = layer_init(nn.Conv2d(32, 64, 4, stride=2)) self.u2 = nn.ModuleList( [ layer_init(nn.Conv2d(32, 64, 4, stride=2, bias=False)) for _ in range(n_prev) ] ) self.c3 = layer_init(nn.Conv2d(64, 64, 3, stride=1)) self.u3 = nn.ModuleList( [ layer_init(nn.Conv2d(64, 64, 3, stride=1, bias=False)) for _ in range(n_prev) ] ) self.a = nn.ReLU() self.flat = nn.Flatten() self.o1 = layer_init(nn.Linear(64 * 7 * 7, out_dim)) self.uo1 = nn.ModuleList( [ layer_init(nn.Linear(64 * 7 * 7, out_dim, bias=False)) for _ in range(n_prev) ] ) # freeze previous models (columns) for m in previous_models: if hasattr(m, "previous_models"): del m.previous_models m.eval() for param in m.parameters(): param.requires_grad = False self.previous_models = previous_models def forward_first(self, x): c1 = self.c1(x) c2 = self.c2(self.a(c1)) c3 = self.c3(self.a(c2)) out = self.o1(self.a(self.flat(c3))) return out, c1, c2, c3 def forward_other(self, x, c1s, c2s, c3s): c1 = self.a(self.c1(x)) assert len(c1s) == len( self.u2 ), "The number of previous layer outputs does not match the number of adapters" h2 = [u(c1s[i]) for i, u in enumerate(self.u2)] c2 = sum([self.c2(c1), *h2]) c2 = self.a(c2) h3 = [u(c2s[i]) for i, u in enumerate(self.u3)] c3 = sum([self.c3(c2), *h3]) c3 = self.a(c3) uo1 = [u(self.flat(c3s[i])) for i, u in enumerate(self.uo1)] out = sum([self.o1(self.flat(c3)), *uo1]) return out, c1, c2, c3 def forward(self, x): if len(self.previous_models) == 0: return self.forward_first(x)[0] # forward first module _, c1, c2, c3 = self.forward_first(x) # forward the rest of the previous modules (if there're some) c1s, c2s, c3s = [c1], [c2], [c3] for model in self.previous_models[1:]: _, c1, c2, c3 = model.forward_other(x, c1s, c2s, c3s) c1s.append(c1) c2s.append(c2) c3s.append(c3) out, _, _, _ = self.forward_other(x, c1s, c2s, c3s) return out
4,944
Python
.py
124
30.258065
87
0.569549
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,740
cnn_encoder.py
mikelma_componet/experiments/atari/models/cnn_encoder.py
import torch.nn as nn class CnnEncoder(nn.Module): def __init__(self, hidden_dim=512, layer_init=lambda x, **kwargs: x): super().__init__() self.network = nn.Sequential( layer_init(nn.Conv2d(4, 32, 8, stride=4)), nn.ReLU(), layer_init(nn.Conv2d(32, 64, 4, stride=2)), nn.ReLU(), layer_init(nn.Conv2d(64, 64, 3, stride=1)), nn.ReLU(), nn.Flatten(), layer_init(nn.Linear(64 * 7 * 7, hidden_dim)), nn.ReLU(), ) def forward(self, x): return self.network(x)
604
Python
.py
17
25.647059
73
0.513699
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,741
dino_simple.py
mikelma_componet/experiments/atari/models/dino_simple.py
import os import numpy as np import torch import torch.nn as nn from torch.distributions.categorical import Categorical from .dino_encoder import DinoEncoder def layer_init(layer, std=np.sqrt(2), bias_const=0.0): torch.nn.init.orthogonal_(layer.weight, std) torch.nn.init.constant_(layer.bias, bias_const) return layer class DinoSimpleAgent(nn.Module): def __init__(self, envs, dino_size, frame_stack, device): super().__init__() self.dino = DinoEncoder(dino_size=dino_size, device=device) self.middle = nn.Sequential( layer_init(nn.Linear(self.dino.embed_dim * frame_stack, 512)), nn.ReLU(), layer_init(nn.Linear(512, 512)), nn.ReLU(), layer_init(nn.Linear(512, 512)), nn.ReLU(), ) self.actor = layer_init(nn.Linear(512, envs.single_action_space.n), std=0.01) self.critic = layer_init(nn.Linear(512, 1), std=1) def get_value(self, x): h = self.middle(self.dino.encode(x * 255.0)) # denormalize return self.critic(h) def get_action_and_value(self, x, action=None): hidden = self.middle(self.dino.encode(x * 255.0)) # denormalize logits = self.actor(hidden) probs = Categorical(logits=logits) if action is None: action = probs.sample() return action, probs.log_prob(action), probs.entropy(), self.critic(hidden) def save(self, dirname, model_name): os.makedirs(dirname, exist_ok=True) torch.save(self.middle, f"{dirname}/{model_name}_middle.pt") torch.save(self.actor, f"{dirname}/{model_name}_actor.pt") torch.save(self.critic, f"{dirname}/{model_name}_critic.pt") def load(dirname, agent_args): model = DinoSimpleAgent(**agent_args) model.middle = torch.load(f"{dirname}/middle.pt") model.actor = torch.load(f"{dirname}/actor.pt") model.critic = torch.load(f"{dirname}/critic.pt") return model
1,997
Python
.py
45
36.711111
85
0.641975
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,742
dino_encoder.py
mikelma_componet/experiments/atari/models/dino_encoder.py
import torch import torchvision.transforms as T class DinoEncoder: def __init__(self, dino_size, device): # see: https://github.com/facebookresearch/dinov2/blob/main/MODEL_CARD.md#model-details if dino_size == "s": self.embed_dim = 384 elif dino_size == "b": self.embed_dim = 768 elif dino_size == "l": self.embed_dim = 1024 elif dino_size == "g": self.embed_dim = 1536 else: print(f"Invalid DINOv2 size {dino_size}. Valid values are s, b, l, and g") self.dino = torch.hub.load( "facebookresearch/dinov2", f"dinov2_vit{dino_size}14_reg" ).to(device) self.transform = T.Normalize( mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225) ) @torch.no_grad() def encode(self, x): # x: (batch, n_stack, h, w, n_channels) batch_size = x.size(0) n_stack = x.size(1) x = torch.flatten( x, start_dim=0, end_dim=1 ) # x: (batch * n_stack, h, w, n_channels) x = x.permute(0, 3, 1, 2) # x: (batch * n_stack, n_channles, h, w) x = self.transform(x) # normalize latent = self.dino(x) latent = latent.resize(batch_size, self.embed_dim * n_stack) return latent
1,321
Python
.py
34
29.764706
95
0.552344
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,743
__init__.py
mikelma_componet/experiments/atari/models/__init__.py
from .cnn_simple import CnnSimpleAgent from .dino_simple import DinoSimpleAgent from .cnn_componet import CnnCompoNetAgent from .progressive_net import ProgressiveNetAgent from .packnet import PackNetAgent
206
Python
.py
5
40.2
48
0.880597
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,744
cnn_simple.py
mikelma_componet/experiments/atari/models/cnn_simple.py
import os import torch import torch.nn as nn import numpy as np from torch.distributions.categorical import Categorical from .cnn_encoder import CnnEncoder def layer_init(layer, std=np.sqrt(2), bias_const=0.0): torch.nn.init.orthogonal_(layer.weight, std) torch.nn.init.constant_(layer.bias, bias_const) return layer class CnnSimpleAgent(nn.Module): def __init__(self, envs): super().__init__() self.network = CnnEncoder(hidden_dim=512, layer_init=layer_init) self.actor = layer_init(nn.Linear(512, envs.single_action_space.n), std=0.01) self.critic = layer_init(nn.Linear(512, 1), std=1) def get_value(self, x): return self.critic(self.network(x)) def get_action_and_value(self, x, action=None): hidden = self.network(x) logits = self.actor(hidden) probs = Categorical(logits=logits) if action is None: action = probs.sample() return action, probs.log_prob(action), probs.entropy(), self.critic(hidden) def save(self, dirname): os.makedirs(dirname, exist_ok=True) torch.save(self.actor, f"{dirname}/actor.pt") torch.save(self.network, f"{dirname}/encoder.pt") torch.save(self.critic, f"{dirname}/critic.pt") def load(dirname, envs, load_critic=True, reset_actor=False, map_location=None): model = CnnSimpleAgent(envs) model.network = torch.load(f"{dirname}/encoder.pt", map_location=map_location) if not reset_actor: model.actor = torch.load(f"{dirname}/actor.pt", map_location=map_location) if load_critic: model.critic = torch.load(f"{dirname}/critic.pt", map_location=map_location) return model
1,727
Python
.py
38
38.447368
88
0.671624
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,745
packnet.py
mikelma_componet/experiments/atari/models/packnet.py
import torch import torch.nn as nn from torch.distributions.categorical import Categorical from .cnn_encoder import CnnEncoder import copy import os import numpy as np def layer_init(layer, std=np.sqrt(2), bias_const=0.0): torch.nn.init.orthogonal_(layer.weight, std) torch.nn.init.constant_(layer.bias, bias_const) return layer class PackNetAgent(nn.Module): def __init__(self, envs, task_id, is_first_task, total_task_num): super().__init__() self.network = PackNet( hidden_dim=512, task_id=task_id, total_task_num=total_task_num, is_first_task=is_first_task, layer_init=layer_init, ) self.num_actions = envs.single_action_space.n self.actor = layer_init(nn.Linear(512, self.num_actions), std=0.01) self.critic = layer_init(nn.Linear(512, 1), std=1) self.retrain_mode = False def get_value(self, x): return self.critic(self.network(x)) def get_action_and_value(self, x, action=None): hidden = self.network(x) logits = self.actor(hidden) probs = Categorical(logits=logits) if action is None: action = probs.sample() return action, probs.log_prob(action), probs.entropy(), self.critic(hidden) def save(self, dirname): # un-do the masking for the current task self.network.set_view(None) os.makedirs(dirname, exist_ok=True) torch.save(self, f"{dirname}/packnet.pt") def load( dirname, task_id=None, restart_actor_critic=False, freeze_bias=True, map_location=None, ): model = torch.load(f"{dirname}/packnet.pt", map_location=map_location) model.retrain_mode = False if task_id is not None: model.network.task_id = task_id if restart_actor_critic: model.actor = layer_init(nn.Linear(512, model.num_actions), std=0.01) model.critic = layer_init(nn.Linear(512, 1), std=1) if freeze_bias: for name, param in model.network.model.named_parameters(): if name.endswith(".bias"): param.requires_grad = False return model def start_retraining(self): if self.retrain_mode: return # nothing to do print("==> PackNet re-training starts!") self.retrain_mode = True self.network.prune() # generate the masks for the current task self.network.set_view(self.network.task_id) def before_update(self): self.network.adjust_gradients(retrain_mode=self.retrain_mode) class PackNet(nn.Module): def __init__( self, hidden_dim, task_id, total_task_num, is_first_task, layer_init=lambda x, **kwargs: x, device="cuda" if torch.cuda.is_available() else "cpu", ): super().__init__() assert task_id > 0, "Task ID must be greater than 0 in PackNet" self.model = CnnEncoder(hidden_dim=hidden_dim, layer_init=layer_init).network self.task_id = task_id self.total_task_num = total_task_num self.prune_percentage = 1 / self.total_task_num self.view = None self.handled_layers = ( [] ) # will contain copies of the original parameters when using views # generate the masks self.masks = [] for name, param in self.model.named_parameters(): if name.endswith(".weight"): self.masks.append( torch.zeros(param.size(), dtype=torch.long, device=device) ) else: self.masks.append(None) # if we're in a tasks that it's not the first, freeze biases if not is_first_task: for name, param in self.model.named_parameters(): if name.endswith(".bias"): param.requires_grad = False @torch.no_grad() def adjust_gradients(self, retrain_mode=False): mask_id = self.task_id if retrain_mode else 0 for p, mask in zip(self.model.parameters(), self.masks): if mask is None: continue p.grad = p.grad * (mask == mask_id) @torch.no_grad() def prune(self): for p, mask in zip(self.model.parameters(), self.masks): if mask is None: continue # sort the unassigned weights from lower to higher magnitudes masked = p * (mask == 0) # only select "free" weights flat = masked.flatten() _sorted, indices = torch.sort( flat.abs(), descending=True ) # sort from max to min magnitude n_prune = int( self.prune_percentage * flat.size(0) ) # number of weights to keep in pruning # create the mask mask.flatten()[indices[:n_prune]] = self.task_id def forward(self, x): return self.model(x) @torch.no_grad() def set_view(self, task_id): if task_id is None and self.view is not None: # restore the original state of the model in the free parameters (not masked) for param_copy, param, mask in zip( self.handled_layers, self.model.parameters(), self.masks ): if param_copy is None: continue m = torch.logical_and( mask <= self.view, mask > 0 ) # pruned=0, not-pruned=1 param.data += param_copy.data * torch.logical_not(m) self.handled_layers = [] self.view = task_id return if len(self.handled_layers) == 0: # save a copy of each (parametrized) layer of the model for param, mask in zip(self.model.parameters(), self.masks): if mask is not None: self.handled_layers.append(copy.deepcopy(param)) else: self.handled_layers.append(None) # apply the masks for p, mask in zip(self.model.parameters(), self.masks): if mask is None: continue # set to zero the parameters that are free (have no mask) or whose mask ID is greater than task_id p.data *= torch.logical_and(mask <= task_id, mask > 0) self.view = task_id
6,428
Python
.py
156
30.634615
110
0.582305
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,746
cnn_componet.py
mikelma_componet/experiments/atari/models/cnn_componet.py
import os import torch import torch.nn as nn import numpy as np from torch.distributions.categorical import Categorical from .cnn_encoder import CnnEncoder import sys, os sys.path.append(os.path.dirname(__file__) + "/../../../") from componet import CompoNet, FirstModuleWrapper def layer_init(layer, std=np.sqrt(2), bias_const=0.0): torch.nn.init.orthogonal_(layer.weight, std) torch.nn.init.constant_(layer.bias, bias_const) return layer class CnnCompoNetAgent(nn.Module): def __init__(self, envs, prevs_paths=[], finetune_encoder=False, map_location=None): super().__init__() hidden_dim = 512 if not finetune_encoder or len(prevs_paths) == 0: self.encoder = CnnEncoder(hidden_dim=hidden_dim, layer_init=layer_init) else: self.encoder = torch.load( f"{prevs_paths[-1]}/encoder.pt", map_location=map_location ) print("==> Encoder loaded from last CompoNet module") self.critic = layer_init(nn.Linear(hidden_dim, 1), std=1) pol_in = hidden_dim if len(prevs_paths) == 0 else hidden_dim * 2 pol = nn.Sequential( layer_init(nn.Linear(pol_in, hidden_dim)), nn.ReLU(), layer_init(nn.Linear(hidden_dim, envs.single_action_space.n), std=0.01), ) if len(prevs_paths) > 0: previous_units = [ torch.load(f"{p}/actor.pt", map_location=map_location) for p in prevs_paths ] self.actor = CompoNet( previous_units=previous_units, input_dim=hidden_dim, # size of the CnnEncoder output hidden_dim=hidden_dim, out_dim=envs.single_action_space.n, internal_policy=pol, ret_probs=True, encoder=self.encoder, ) self.is_compo = True else: self.actor = FirstModuleWrapper( model=pol, ret_probs=True, encoder=self.encoder ) self.is_compo = False def get_value(self, x): return self.critic(self.encoder(x)) def get_action_and_value( self, x, action=None, log_writter=None, global_step=None, prevs_to_noise=0 ): if not self.is_compo or global_step is None or log_writter is None: p, _phi, hidden = self.actor( x, ret_encoder_out=True, prevs_to_noise=prevs_to_noise ) else: p, _phi, hidden, att_in, att_out, int_pol, head_out = self.actor( x, ret_encoder_out=True, return_atts=True, ret_int_pol=True, ret_head_out=True, prevs_to_noise=prevs_to_noise, ) with torch.no_grad(): # log attention values for i, v in enumerate(att_in.mean(0)[0].detach()): log_writter.add_scalar(f"charts/att_in_{i}", v.item(), global_step) for i, v in enumerate(att_out.mean(0)[0].detach()): log_writter.add_scalar(f"charts/att_out_{i}", v.item(), global_step) _, a_int_pol = int_pol.max(-1) _, a_head_out = head_out.max(-1) _, a_out = p.max(-1) bs = a_out.size(0) log_writter.add_scalar( f"charts/out_matches_int_pol", ((a_out == a_int_pol).sum() / bs).item(), global_step, ) log_writter.add_scalar( f"charts/out_matches_head_out", ((a_out == a_head_out).sum() / bs).item(), global_step, ) log_writter.add_scalar( f"charts/int_pol_matches_head", ((a_int_pol == a_head_out).sum() / bs).item(), global_step, ) probs = Categorical(probs=p) if action is None: action = probs.sample() return action, probs.log_prob(action), probs.entropy(), self.critic(hidden) def save(self, dirname): os.makedirs(dirname, exist_ok=True) if hasattr(self.actor, "previous_units"): del self.actor.previous_units torch.save(self.actor, f"{dirname}/actor.pt") torch.save(self.critic, f"{dirname}/crititc.pt") torch.save(self.encoder, f"{dirname}/encoder.pt") def load(dirname, envs, prevs_paths=[], map_location=None): print("Loading previous:", prevs_paths) model = CnnCompoNetAgent( envs=envs, prevs_paths=prevs_paths, map_location=map_location ) model.encoder = torch.load(f"{dirname}/encoder.pt", map_location=map_location) # load the state dict of the actor actor = torch.load(f"{dirname}/actor.pt", map_location=map_location) curr = model.actor.state_dict() other = actor.state_dict() for k in other: curr[k] = other[k] model.actor.load_state_dict(curr) model.critic = torch.load(f"{dirname}/crititc.pt", map_location=map_location) return model
5,209
Python
.py
120
31.308333
88
0.55218
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,747
run_sac.py
mikelma_componet/experiments/meta-world/run_sac.py
# docs and experiment results can be found at https://docs.cleanrl.dev/rl-algorithms/sac/#sac_continuous_actionpy import os import random import time from dataclasses import dataclass import gymnasium as gym import numpy as np import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import tyro import pathlib from torch.utils.tensorboard import SummaryWriter from typing import Literal, Optional, Tuple from models import shared, SimpleAgent, CompoNetAgent, PackNetAgent, ProgressiveNetAgent from tasks import get_task, get_task_name from stable_baselines3.common.buffers import ReplayBuffer @dataclass class Args: model_type: Literal["simple", "finetune", "componet", "packnet", "prognet"] """The name of the NN model to use for the agent""" save_dir: Optional[str] = None """If provided, the model will be saved in the given directory""" prev_units: Tuple[pathlib.Path, ...] = () """Paths to the previous models. Not required when model_type is `simple` or `packnet` or `prognet`""" exp_name: str = os.path.basename(__file__)[: -len(".py")] """the name of this experiment""" seed: int = 1 """seed of the experiment""" torch_deterministic: bool = True """if toggled, `torch.backends.cudnn.deterministic=False`""" cuda: bool = True """if toggled, cuda will be enabled by default""" track: bool = False """if toggled, this experiment will be tracked with Weights and Biases""" wandb_project_name: str = "cw-sac" """the wandb's project name""" wandb_entity: str = None """the entity (team) of wandb's project""" capture_video: bool = False """whether to capture videos of the agent performances (check out `videos` folder)""" # Algorithm specific arguments task_id: int = 0 """ID number of the task""" eval_every: int = 10_000 """Evaluate the agent in determinstic mode every X timesteps""" num_evals: int = 10 """Number of times to evaluate the agent""" total_timesteps: int = int(1e6) """total timesteps of the experiments""" buffer_size: int = int(1e6) """the replay memory buffer size""" gamma: float = 0.99 """the discount factor gamma""" tau: float = 0.005 """target smoothing coefficient (default: 0.005)""" batch_size: int = 128 """the batch size of sample from the reply memory""" learning_starts: int = 5_000 """timestep to start learning""" random_actions_end: int = 10_000 """timesteps to take actions randomly""" policy_lr: float = 1e-3 """the learning rate of the policy network optimizer""" q_lr: float = 1e-3 """the learning rate of the Q network network optimizer""" policy_frequency: int = 2 """the frequency of training policy (delayed)""" target_network_frequency: int = 1 # Denis Yarats' implementation delays this by 2. """the frequency of updates for the target nerworks""" noise_clip: float = 0.5 """noise clip parameter of the Target Policy Smoothing Regularization""" alpha: float = 0.2 """Entropy regularization coefficient.""" autotune: bool = True """automatic tuning of the entropy coefficient""" def make_env(task_id): def thunk(): env = get_task(task_id) env = gym.wrappers.RecordEpisodeStatistics(env) return env return thunk # ALGO LOGIC: initialize agent here: class SoftQNetwork(nn.Module): def __init__(self, envs): super().__init__() self.fc = shared( np.array(envs.observation_space.shape).prod() + np.prod(envs.action_space.shape) ) self.fc_out = nn.Linear(256, 1) def forward(self, x, a): x = torch.cat([x, a], 1) x = self.fc(x) x = self.fc_out(x) return x LOG_STD_MAX = 2 LOG_STD_MIN = -20 class Actor(nn.Module): def __init__(self, envs, model): super().__init__() self.model = model # action rescaling self.register_buffer( "action_scale", torch.tensor( (envs.single_action_space.high - envs.single_action_space.low) / 2.0, dtype=torch.float32, ), ) self.register_buffer( "action_bias", torch.tensor( (envs.single_action_space.high + envs.single_action_space.low) / 2.0, dtype=torch.float32, ), ) def forward(self, x, **kwargs): mean, log_std = self.model(x, **kwargs) log_std = torch.tanh(log_std) log_std = LOG_STD_MIN + 0.5 * (LOG_STD_MAX - LOG_STD_MIN) * ( log_std + 1 ) # From SpinUp / Denis Yarats return mean, log_std def get_action(self, x, **kwargs): mean, log_std = self(x, **kwargs) std = log_std.exp() normal = torch.distributions.Normal(mean, std) x_t = normal.rsample() # for reparameterization trick (mean + std * N(0,1)) y_t = torch.tanh(x_t) action = y_t * self.action_scale + self.action_bias log_prob = normal.log_prob(x_t) # Enforcing Action Bound log_prob -= torch.log(self.action_scale * (1 - y_t.pow(2)) + 1e-6) log_prob = log_prob.sum(1, keepdim=True) mean = torch.tanh(mean) * self.action_scale + self.action_bias return action, log_prob, mean @torch.no_grad() def eval_agent(agent, test_env, num_evals, global_step, writer, device): obs, _ = test_env.reset() avg_ep_ret = 0 avg_success = 0 ep_ret = 0 for _ in range(num_evals): while True: obs = torch.Tensor(obs).to(device).unsqueeze(0) action, _ = agent(obs) obs, reward, termination, truncation, info = test_env.step( action[0].cpu().numpy() ) ep_ret += reward if termination or truncation: avg_success += info["success"] avg_ep_ret += ep_ret # resets obs, _ = test_env.reset() ep_ret = 0 break avg_ep_ret /= num_evals avg_success /= num_evals print(f"\nTEST: ep_ret={avg_ep_ret}, success={avg_success}\n") writer.add_scalar("charts/test_episodic_return", avg_ep_ret, global_step) writer.add_scalar("charts/test_success", avg_success, global_step) if __name__ == "__main__": args = tyro.cli(Args) run_name = f"task_{args.task_id}__{args.model_type}__{args.exp_name}__{args.seed}" print(f"\n*** Run name: {run_name} ***\n") if args.track: import wandb wandb.init( project=args.wandb_project_name, entity=args.wandb_entity, sync_tensorboard=True, config=vars(args), name=run_name, monitor_gym=True, save_code=True, ) writer = SummaryWriter(f"runs/{run_name}") writer.add_text( "hyperparameters", "|param|value|\n|-|-|\n%s" % ("\n".join([f"|{key}|{value}|" for key, value in vars(args).items()])), ) # TRY NOT TO MODIFY: seeding random.seed(args.seed) np.random.seed(args.seed) torch.manual_seed(args.seed) torch.backends.cudnn.deterministic = args.torch_deterministic device = torch.device("cuda" if torch.cuda.is_available() and args.cuda else "cpu") print(f"*** Device: {device}") # env setup envs = gym.vector.SyncVectorEnv([make_env(args.task_id)]) assert isinstance( envs.single_action_space, gym.spaces.Box ), "only continuous action space is supported" max_action = float(envs.single_action_space.high[0]) # select the model to use as the agent obs_dim = np.array(envs.single_observation_space.shape).prod() act_dim = np.prod(envs.single_action_space.shape) print(f"*** Loading model `{args.model_type}` ***") if args.model_type in ["finetune", "componet"]: assert ( len(args.prev_units) > 0 ), f"Model type {args.model_type} requires at least one previous unit" if args.model_type == "simple": model = SimpleAgent(obs_dim=obs_dim, act_dim=act_dim).to(device) elif args.model_type == "finetune": model = SimpleAgent.load( args.prev_units[0], map_location=device, reset_heads=True ).to(device) elif args.model_type == "componet": model = CompoNetAgent( obs_dim=obs_dim, act_dim=act_dim, prev_paths=args.prev_units, map_location=device, ).to(device) elif args.model_type == "packnet": packnet_retrain_start = args.total_timesteps - int(args.total_timesteps * 0.2) if len(args.prev_units) == 0: model = PackNetAgent( obs_dim=obs_dim, act_dim=act_dim, task_id=args.task_id, total_task_num=20, device=device, ).to(device) else: model = PackNetAgent.load( args.prev_units[0], task_id=args.task_id + 1, restart_heads=True, freeze_bias=True, map_location=device, ).to(device) elif args.model_type == "prognet": model = ProgressiveNetAgent( obs_dim=obs_dim, act_dim=act_dim, prev_paths=args.prev_units, map_location=device, ).to(device) actor = Actor(envs, model).to(device) qf1 = SoftQNetwork(envs).to(device) qf2 = SoftQNetwork(envs).to(device) qf1_target = SoftQNetwork(envs).to(device) qf2_target = SoftQNetwork(envs).to(device) qf1_target.load_state_dict(qf1.state_dict()) qf2_target.load_state_dict(qf2.state_dict()) q_optimizer = optim.Adam( list(qf1.parameters()) + list(qf2.parameters()), lr=args.q_lr ) actor_optimizer = optim.Adam(list(actor.parameters()), lr=args.policy_lr) # Automatic entropy tuning if args.autotune: target_entropy = -torch.prod( torch.Tensor(envs.action_space.shape).to(device) ).item() log_alpha = torch.zeros(1, requires_grad=True, device=device) alpha = log_alpha.exp().item() a_optimizer = optim.Adam([log_alpha], lr=args.q_lr) else: alpha = args.alpha envs.single_observation_space.dtype = np.float32 rb = ReplayBuffer( args.buffer_size, envs.single_observation_space, envs.single_action_space, device, handle_timeout_termination=False, ) start_time = time.time() # TRY NOT TO MODIFY: start the game obs, _ = envs.reset(seed=args.seed) for global_step in range(args.total_timesteps): # ALGO LOGIC: put action logic here if global_step < args.random_actions_end: actions = np.array( [envs.single_action_space.sample() for _ in range(envs.num_envs)] ) else: if args.model_type == "componet" and global_step % 1000 == 0: actions, _, _ = actor.get_action( torch.Tensor(obs).to(device), writer=writer, global_step=global_step, ) else: actions, _, _ = actor.get_action(torch.Tensor(obs).to(device)) actions = actions.detach().cpu().numpy() # TRY NOT TO MODIFY: execute the game and log data. next_obs, rewards, terminations, truncations, infos = envs.step(actions) # TRY NOT TO MODIFY: record rewards for plotting purposes if "final_info" in infos: for i, info in enumerate(infos["final_info"]): print( f"global_step={global_step}, episodic_return={info['episode']['r']}, success={info['success']}" ) writer.add_scalar( "charts/episodic_return", info["episode"]["r"], global_step ) writer.add_scalar( "charts/episodic_length", info["episode"]["l"], global_step ) writer.add_scalar("charts/success", info["success"], global_step) break # TRY NOT TO MODIFY: save data to reply buffer; handle `final_observation` real_next_obs = next_obs.copy() for idx, trunc in enumerate(truncations): if trunc: real_next_obs[idx] = infos["final_observation"][idx] rb.add(obs, real_next_obs, actions, rewards, terminations, infos) # TRY NOT TO MODIFY: CRUCIAL step easy to overlook obs = next_obs # ALGO LOGIC: training. if global_step > args.learning_starts: data = rb.sample(args.batch_size) with torch.no_grad(): next_state_actions, next_state_log_pi, _ = actor.get_action( data.next_observations ) qf1_next_target = qf1_target(data.next_observations, next_state_actions) qf2_next_target = qf2_target(data.next_observations, next_state_actions) min_qf_next_target = ( torch.min(qf1_next_target, qf2_next_target) - alpha * next_state_log_pi ) next_q_value = data.rewards.flatten() + ( 1 - data.dones.flatten() ) * args.gamma * (min_qf_next_target).view(-1) qf1_a_values = qf1(data.observations, data.actions).view(-1) qf2_a_values = qf2(data.observations, data.actions).view(-1) qf1_loss = F.mse_loss(qf1_a_values, next_q_value) qf2_loss = F.mse_loss(qf2_a_values, next_q_value) qf_loss = qf1_loss + qf2_loss # optimize the model q_optimizer.zero_grad() qf_loss.backward() q_optimizer.step() if global_step % args.policy_frequency == 0: # TD 3 Delayed update support for _ in range( args.policy_frequency ): # compensate for the delay by doing 'actor_update_interval' instead of 1 pi, log_pi, _ = actor.get_action(data.observations) qf1_pi = qf1(data.observations, pi) qf2_pi = qf2(data.observations, pi) min_qf_pi = torch.min(qf1_pi, qf2_pi) actor_loss = ((alpha * log_pi) - min_qf_pi).mean() actor_optimizer.zero_grad() actor_loss.backward() if args.model_type == "packnet": if global_step >= packnet_retrain_start: # can be called multiple times, only the first counts actor.model.start_retraining() actor.model.before_update() actor_optimizer.step() if args.autotune: with torch.no_grad(): _, log_pi, _ = actor.get_action(data.observations) alpha_loss = ( -log_alpha.exp() * (log_pi + target_entropy) ).mean() a_optimizer.zero_grad() alpha_loss.backward() a_optimizer.step() alpha = log_alpha.exp().item() # update the target networks if global_step % args.target_network_frequency == 0: for param, target_param in zip( qf1.parameters(), qf1_target.parameters() ): target_param.data.copy_( args.tau * param.data + (1 - args.tau) * target_param.data ) for param, target_param in zip( qf2.parameters(), qf2_target.parameters() ): target_param.data.copy_( args.tau * param.data + (1 - args.tau) * target_param.data ) if global_step % 100 == 0: writer.add_scalar( "losses/qf1_values", qf1_a_values.mean().item(), global_step ) writer.add_scalar( "losses/qf2_values", qf2_a_values.mean().item(), global_step ) writer.add_scalar("losses/qf1_loss", qf1_loss.item(), global_step) writer.add_scalar("losses/qf2_loss", qf2_loss.item(), global_step) writer.add_scalar("losses/qf_loss", qf_loss.item() / 2.0, global_step) writer.add_scalar("losses/actor_loss", actor_loss.item(), global_step) writer.add_scalar("losses/alpha", alpha, global_step) print("SPS:", int(global_step / (time.time() - start_time))) writer.add_scalar( "charts/SPS", int(global_step / (time.time() - start_time)), global_step, ) if args.autotune: writer.add_scalar( "losses/alpha_loss", alpha_loss.item(), global_step ) [ eval_agent(actor, envs.envs[i], args.num_evals, global_step, writer, device) for i in range(envs.num_envs) ] envs.close() writer.close() if args.save_dir is not None: print(f"Saving trained agent in `{args.save_dir}` with name `{run_name}`") actor.model.save(dirname=f"{args.save_dir}/{run_name}")
17,584
Python
.py
413
31.842615
115
0.569851
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,748
process_results.py
mikelma_componet/experiments/meta-world/process_results.py
from tensorboard.backend.event_processing import event_accumulator import pandas as pd import pathlib from tqdm import tqdm import numpy as np import matplotlib.pyplot as plt from matplotlib.lines import Line2D import os, sys import argparse from tabulate import tabulate METHOD_NAMES = { "simple": "Baseline", "finetune": "FT", "componet": "CompoNet", "prognet": "ProgressiveNet", "packnet": "PackNet", } def parse_args(): # fmt: off parser = argparse.ArgumentParser() parser.add_argument("--runs-dir", default="runs_all", type=str, help="directory where the tensorboard data is stored") parser.add_argument("--no-cache", default=False, action="store_true", help="wheter to disable the cache option. If not provided and `--save-dir` exists, skips processing tensorboard files") parser.add_argument("--save-csv", default="data/agg_results.csv", type=str, help="filename of the CSV to store the processed tensorboard results. Once processed, can be used as cache.") parser.add_argument("--smoothing-window", type=int, default=100) parser.add_argument("--eval-csv", type=str, default="data/eval_results.csv", help="path to the CSV where the results of evaluations are stored. If the file doesn't exist, forgetting is not computed.") parser.add_argument("--no-plots", default=False, action="store_true") # fmt: on return parser.parse_args() def parse_metadata(ea): md = ea.Tensors("hyperparameters/text_summary")[0] md_bytes = md.tensor_proto.SerializeToString() # remove first non-ascii characters and parse start = md_bytes.index(b"|") md_str = md_bytes[start:].decode("ascii") md = {} for row in md_str.split("\n")[2:]: s = row.split("|")[1:-1] k = s[0] if s[1].isdigit(): v = int(s[1]) elif s[1].replace(".", "").isdigit(): v = float(s[1]) elif s[1] == "True" or s[1] == "False": v = s[1] == "True" else: v = s[1] md[k] = v return md def parse_tensorboard(path, scalars, single_pts=[]): """returns a dictionary of pandas dataframes for each requested scalar""" ea = event_accumulator.EventAccumulator( path, size_guidance={event_accumulator.SCALARS: 0}, ) _absorb_print = ea.Reload() # make sure the scalars are in the event accumulator tags if sum([s not in ea.Tags()["scalars"] for s in scalars]) > 0: print(f"** Scalar not found. Skipping file {path}") return None # assert all( # s in ea.Tags()["scalars"] for s in scalars # ), f"some scalars were not found in the event accumulator: {ea.Tags()['scalars']}" md = parse_metadata(ea) for name in single_pts: if name in ea.Tags()["scalars"]: md[name] = pd.DataFrame(ea.Scalars(name))["value"][0] return {k: pd.DataFrame(ea.Scalars(k)) for k in scalars}, md def smooth_avg(df, xkey, ykey, w=20): g = df.groupby(xkey)[ykey] mean = g.mean().rolling(window=w).mean() std = g.std().rolling(window=w).mean() y = mean.values y_std = std.values x = mean.reset_index()[xkey].values return x, y, y_std def areas_up_down(method_x, method_y, baseline_x, baseline_y): up_idx = method_y > baseline_y down_idx = method_y < baseline_y assert ( method_x == baseline_x ).all(), "The X axis of the baseline and method must be equal." x = method_x area_up = np.trapz(y=method_y[up_idx], x=x[up_idx]) - np.trapz( y=baseline_y[up_idx], x=x[up_idx] ) area_down = np.trapz(y=baseline_y[down_idx], x=x[down_idx]) - np.trapz( y=method_y[down_idx], x=x[down_idx] ) return area_up, area_down def remove_nan(x, y): no_nan = ~np.isnan(y) return x[no_nan], y[no_nan] def compute_forward_transfer(df, methods, smoothing_window): methods = methods.copy() methods.remove("simple") table = [] results = {} for task_id in range(20): # do not compute forward transfer for the first task if task_id == 0: table.append([0] + [None] * len(methods)) continue baseline = df[ (df["model_type"] == "simple") & (df["task_id"] == (task_id % 10)) ] # get the curve of the `simple` method x_baseline, y_baseline, _ = smooth_avg( baseline, xkey="step", ykey="value", w=smoothing_window ) x_baseline, y_baseline = remove_nan(x_baseline, y_baseline) baseline_area_down = np.trapz(y=y_baseline, x=x_baseline) baseline_area_up = np.max(x_baseline) - baseline_area_down table_row = [task_id] for j, name in enumerate(methods): method = df[(df["model_type"] == name) & (df["task_id"] == task_id)] x_method, y_method, _ = smooth_avg( method, xkey="step", ykey="value", w=smoothing_window ) x_method, y_method = remove_nan(x_method, y_method) # this can happen if a method hasn't the results for all tasks if len(x_baseline) > len(x_method): table_row.append(None) continue area_up, area_down = areas_up_down( x_method, y_method, x_baseline, y_baseline, ) ft = (area_up - area_down) / baseline_area_up table_row.append(round(ft, 2)) if methods[j] not in results.keys(): results[methods[j]] = [] results[methods[j]].append(ft) table.append(table_row) table.append([None] * len(table_row)) row = ["Avg."] for i in range(len(methods)): vals = [] for r in table[1:]: v = r[i + 1] if v is not None: vals.append(v) mean = np.mean(vals) std = np.std(vals) row.append((round(mean, 2), round(std, 2))) table.append(row) print("\n== FORWARD TRANSFER ==") print( tabulate( table, headers=["Task ID"] + methods, tablefmt="rounded_outline", ) ) print("\n") return results def compute_performance(df, methods, col="charts/test_success"): table = [] avgs = [[] for _ in range(len(methods))] results = {} eval_steps = df["step"].unique()[-10] for i in range(20): row = [i] for j, m in enumerate(methods): task_id = i if m != "simple" else i % 10 method = "simple" if task_id == 0 and m in ["componet", "finetune"] else m s = df[ (df["task_id"] == task_id) & (df["model_type"] == method) & (df["step"] >= eval_steps) ]["value"].values if len(s) == 0: s = np.array([np.nan]) if methods[j] not in results.keys(): results[methods[j]] = [] results[methods[j]].append((s.mean(), s.std())) avg = round(s.mean(), 2) std = round(s.std(), 2) row.append((avg, std)) if not np.isnan(s).any() and i > 0: avgs[j] += list(s) table.append(row) avgs = [(round(np.mean(v), 2), round(np.std(v), 2)) for v in avgs] table.append([None] * len(row)) table.append(["Avg."] + avgs) for i in range(len(table)): for j in range(len(table[0])): e = table[i][j] if type(e) != tuple: continue if np.isnan(e[0]): table[i][j] = None print("\n== PERFORMANCE ==") print( tabulate( table, headers=["Task ID"] + methods, tablefmt="rounded_outline", ) ) print("\n") return results def count(df, methods): counts = ( df.groupby(["task_id", "model_type"])["seed"].unique().apply(lambda x: len(x)) ) counts = counts.reset_index() table = [] all_vals = [] for task_id in range(20): row = [task_id] for method in methods: c = counts[ (counts["task_id"] == task_id) & (counts["model_type"] == method) ] val = c["seed"].iloc[0] if not c.empty else None row.append(val) if val is not None: all_vals.append(val) table.append(row) s = sum(all_vals) total = len(methods) * 20 * 10 - (12 * 10) print(f"\n\n-----------------------------------") print(f" Total percentage: {round(100*s/total, 3)}% [{s}/{total}]") print(f"-----------------------------------\n\n") print( tabulate( table, headers=["Task ID"] + methods, tablefmt="rounded_outline", ) ) def process_eval(df, perf_data): perf = {} forg = {} for method in df["algorithm"].unique(): s = df[df["algorithm"] == method].groupby("test task")["success"] avgs = s.mean().reset_index().sort_values(by=["test task"]) stds = s.std().reset_index().sort_values(by=["test task"]) perf[method] = {} perf[method]["avgs"] = list(avgs["success"]) perf[method]["stds"] = list(stds["success"]) print(f"** Eval performance: {method}") [ print(f"({round(m, 2)}, {round(s, 2)})", end=" ") for m, s in zip(perf[method]["avgs"], perf[method]["stds"]) ] print( f"\nAvg. and std.: {round(np.mean(perf[method]['avgs']), 2)} {round(np.std(perf[method]['avgs']), 2)} " ) print() all_forgs = [] forg[method] = [] for i in range(len(avgs)): prev = perf_data[method][i][0] lasts = df[(df["algorithm"] == method) & (df["test task"] == i)][ "success" ].values f = prev - lasts all_forgs += list(f) forg[method].append((np.mean(prev - lasts), np.std(prev - lasts))) print(f"** Eval forgetting: {method}") [print(f"{round(m, 2)} [{round(s, 2)}]", end=" ") for m, s in forg[method]] print( f" => Avg. and std.: {round(np.mean(all_forgs), 2)} [{round(np.std(all_forgs), 2)}]" ) print("\n") return perf, forg if __name__ == "__main__": sys.path.append("../../") from utils import style args = parse_args() # hardcoded settings scalar = "charts/success" final_success = "charts/test_success" total_timesteps = 1e6 methods = ["simple", "componet", "finetune", "prognet", "packnet"] fancy_names = ["Baseline", "CompoNet", "FT", "ProgressiveNet", "PackNet"] method_colors = ["darkgray", "tab:blue", "tab:orange", "tab:green", "tab:purple"] # # Extract data from tensorboard results to an actually useful CSV # exists = os.path.exists(args.save_csv) if args.no_cache or (not exists and not args.no_cache): dfs = [] for path in tqdm(list(pathlib.Path(args.runs_dir).rglob("*events.out*"))): # print("*** Processing ", path) res = parse_tensorboard(str(path), [scalar], [final_success]) if res is not None: dic, md = res else: print("No data. Skipping...") continue df = dic[scalar] df = df[["step", "value"]] df["seed"] = md["seed"] df["task_id"] = md["task_id"] df["model_type"] = md["model_type"] if final_success in md: df[final_success] = md[final_success] dfs.append(df) df = pd.concat(dfs) df.to_csv(args.save_csv, index=False) else: print(f"\n\nReloading cache data from: {args.save_csv}") df = pd.read_csv(args.save_csv) # # Compute performance and forward transfer # count(df, methods) data_perf = compute_performance(df, methods) if os.path.exists(args.eval_csv): eval_perf, eval_forg = process_eval(pd.read_csv(args.eval_csv), data_perf) ft_data = compute_forward_transfer(df, methods, args.smoothing_window) # # Save summary CSV # fname = f"summary_data_mw.csv" with open(fname, "w") as f: f.write("env,method,task id,perf,perf std,ft,forg,forg std\n") for task_id in range(20): for method in df["model_type"].unique(): if method in ["finetune", "simple"]: perf = eval_perf[method]["avgs"][task_id % 10] perf_std = eval_perf[method]["stds"][task_id % 10] forg, forg_std = eval_forg[method][task_id % 10] else: perf, perf_std = data_perf[method][task_id] forg, forg_std = 0, 0 if method == "simple" or task_id == 0: ft = 0 else: ft = ft_data[method][task_id - 1] f.write( f"metaworld,{METHOD_NAMES[method]},{task_id},{perf},{perf_std},{ft},{forg},{forg_std}\n" ) print(f"\n*** A summary of the results has been saved to `{fname}` ***\n") if args.no_plots: quit() # # Plotting # assert len(methods) == len( method_colors ), "Number of colors must match number of methods" fig, axes = plt.subplots(nrows=len(methods) + 1, figsize=(10, 8)) # # Plot all the method together # ax = axes[0] for env in range(20): # print(f"* task {env}:") for method, color in zip(methods, method_colors): task_id = env if method != "simple" else env % 10 s = df[(df["model_type"] == method) & (df["task_id"] == task_id)] offset = env * total_timesteps # this happens if an algorithm is not run for a task if s.empty: ax.plot([offset], [0], c="white") continue x, y, std = smooth_avg( s, xkey="step", ykey="value", w=args.smoothing_window ) ax.plot(x + offset, y, c=color, linewidth=0.8) ax.set_ylabel("Success") ax.set_xticks( np.arange(20) * 1e6, [f"{i}" for i in range(20)], fontsize=7, color="dimgray" ) ax.vlines( x=np.arange(20) * 1e6, ymin=0.0, ymax=1, colors="tab:gray", alpha=0.3, linestyles="dashed", linewidths=0.7, ) style(fig, ax=ax, legend=False, grid=False, ax_math_ticklabels=False) # # Plot all methods separately # for i, (method, color) in enumerate(zip(methods, method_colors)): ax = axes[i + 1] ax.vlines( x=np.arange(20) * 1e6, ymin=0.0, ymax=1, colors="tab:gray", alpha=0.3, linestyles="dashed", linewidths=0.7, ) ax.set_xticks( np.arange(20) * 1e6, [f"{i}" for i in range(20)], fontsize=7, color="dimgray", ) ax.set_ylabel(f"{fancy_names[i]}\n\nSuccess") for env in range(20): task_id = env if method != "simple" else env % 10 m = "simple" if env == 0 and method in ["componet", "finetune"] else method s = df[(df["model_type"] == m) & (df["task_id"] == task_id)] offset = env * total_timesteps # this happens if an algorithm is not run for a task if s.empty: if method == "simple": print(f"Empty in simple: task={task_id}") ax.plot([offset], [0], c="white") continue x, y, std = smooth_avg( s, xkey="step", ykey="value", w=args.smoothing_window ) ax.plot(x + offset, y, c=color, linewidth=0.8) ax.fill_between( x + offset, np.maximum(y - std, 0), np.minimum(y + std, 1.0), alpha=0.3, color=color, ) style(fig, ax=ax, legend=False, grid=False, ax_math_ticklabels=False) # only applied to the last `ax` (plot) ax.set_xlabel("Task ID") lines = [Line2D([0], [0], color=c) for c in method_colors] fig.legend( lines, fancy_names, fancybox=False, frameon=False, loc="outside lower center", ncols=len(methods), ) plt.savefig(f"success_curves_metaworld.pdf", pad_inches=0, bbox_inches="tight") plt.show()
16,627
Python
.py
440
28.447727
131
0.536329
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,749
transferer_matrix.py
mikelma_componet/experiments/meta-world/transferer_matrix.py
from tensorboard.backend.event_processing import event_accumulator import matplotlib.pyplot as plt import seaborn as sns import pandas as pd import pathlib from tqdm import tqdm import numpy as np import os from argparse import ArgumentParser from process_results import ( parse_metadata, parse_tensorboard, smooth_avg, remove_nan, areas_up_down, ) def parse_args(): # fmt: off parser = ArgumentParser() parser.add_argument("--runs-dir", type=str, default="runs", help="directory where the TensorBoard logs are stored") parser.add_argument("--save-csv", type=str, default="data/data_transfer_matrix_raw.csv", help="directory where the TensorBoard logs are stored") parser.add_argument("--smoothing-window", type=int, default=100, help="smoothing window for the success rate curves. \ Defaults to the value used in processing meta-world runs.") # fmt: on return parser.parse_args() def reference_transfer(F): n = F.shape[0] s = [] for i in range(1, n): r = [] for j in range(i): r.append(F[j, i]) s.append(max(r)) return np.sum(s) / n if __name__ == "__main__": scalar = "charts/success" args = parse_args() if not os.path.exists(args.save_csv): dfs = [] for path in tqdm(list(pathlib.Path(args.runs_dir).rglob("*events.out*"))): # print(path) res = parse_tensorboard(str(path), [scalar]) if res is not None: dic, md = res else: print("No data. Skipping...") continue first_task = md["task_id"] seed = md["seed"] model_type = md["model_type"] if model_type == "finetune": second_task = int(md["prev_units"][12:-4].split("_")[1]) else: second_task = None df = dic[scalar] df["first task"] = first_task df["second task"] = second_task df["seed"] = seed df["model"] = model_type dfs.append(df) df = pd.concat(dfs) df.to_csv(args.save_csv, index=False) else: print(f"Using cache CSV at: {args.save_csv}") df = pd.read_csv(args.save_csv) # # Compute forward transfers # F = np.zeros((10, 10)) for first_task in range(10): for second_task in range(10): baseline = df[(df["model"] == "simple") & (df["first task"] == second_task)] method = df[ (df["model"] == "finetune") & (df["first task"] == first_task) & (df["second task"] == second_task) ] # get the curve of the `simple` method x_baseline, y_baseline, _ = smooth_avg( baseline, xkey="step", ykey="value", w=args.smoothing_window ) x_baseline, y_baseline = remove_nan(x_baseline, y_baseline) baseline_area_down = np.trapz(y=y_baseline, x=x_baseline) baseline_area_up = np.max(x_baseline) - baseline_area_down x_method, y_method, _ = smooth_avg( method, xkey="step", ykey="value", w=args.smoothing_window ) x_method, y_method = remove_nan(x_method, y_method) # this can happen if a method hasn't the results for all tasks if len(x_baseline) > len(x_method): print(f"Skipping first_task={first_task}, second_task={second_task}") continue area_up, area_down = areas_up_down( x_method, y_method, x_baseline, y_baseline, ) ft = (area_up - area_down) / baseline_area_up F[first_task, second_task] = ft rt = reference_transfer(F) print("\n=> Reference transfer:", rt) print() fs = 14 plt.rc("axes", labelsize=fs) # fontsize of the x and y labels plt.rc("xtick", labelsize=fs) # fontsize of the tick labels plt.rc("ytick", labelsize=fs) # fontsize of the tick labels F = np.round(F, 2) sns.heatmap(F, annot=True, cmap="RdYlGn", center=0.0, vmin=-1, vmax=1) plt.xlabel("Second task") plt.ylabel("First task") plt.savefig(f"transfer_matrix_metaworld.pdf", pad_inches=0, bbox_inches="tight") plt.show()
4,397
Python
.py
116
28.681034
92
0.568038
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,750
tasks.py
mikelma_componet/experiments/meta-world/tasks.py
import numpy as np single_tasks = [ "hammer-v2", "push-wall-v2", "faucet-close-v2", "push-back-v2", "stick-pull-v2", "handle-press-side-v2", "push-v2", "shelf-place-v2", "window-close-v2", "peg-unplug-side-v2", ] tasks = single_tasks + single_tasks def get_task_name(task_id): return tasks[task_id] def get_task(task_id, render=False): from metaworld.envs import ALL_V2_ENVIRONMENTS_GOAL_OBSERVABLE name = tasks[task_id] + "-goal-observable" env_cls = ALL_V2_ENVIRONMENTS_GOAL_OBSERVABLE[name] env = env_cls(seed=np.random.randint(0, 1024)) if render: env.render_mode = "human" env._freeze_rand_vec = False return env if __name__ == "__main__": env = get_task(0, render=True) for _ in range(200): obs, _ = env.reset() # reset environment a = env.action_space.sample() # sample an action # step the environment with the sampled random action obs, reward, terminated, truncated, info = env.step(a) if terminated: break
1,074
Python
.py
34
26.029412
66
0.636098
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,751
test_agent.py
mikelma_componet/experiments/meta-world/test_agent.py
import gymnasium as gym import numpy as np import torch from models import shared, SimpleAgent, CompoNetAgent, PackNetAgent, ProgressiveNetAgent from tasks import get_task, get_task_name import argparse import os from run_sac import Actor import random def parse_args(): parser = argparse.ArgumentParser() # fmt: off parser.add_argument("--load", type=str, required=True) parser.add_argument("--task-id", type=int, required=False, default=None) parser.add_argument("--seed", type=int, required=False, default=None) parser.add_argument("--num-episodes", type=int, default=10) parser.add_argument('--render', default=False, action='store_true') parser.add_argument('--csv', default=None, type=str) # fmt: on return parser.parse_args() def parse_load_name(path): name = os.path.basename(path) s = name.split("__") method = s[1] seed = int(s[-1]) task = int(s[0].split("_")[-1]) return method, seed, task def make_env(task_id, render_human=False): def thunk(): env = get_task(task_id) if render_human: env.render_mode = "human" env = gym.wrappers.RecordEpisodeStatistics(env) return env return thunk @torch.no_grad() def eval_agent(agent, test_env, num_evals, device): obs, _ = test_env.reset() ep_rets = [] successes = [] ep_ret = 0 for _ in range(num_evals): while True: obs = torch.Tensor(obs).to(device).unsqueeze(0) action, _ = agent(obs) action = action[0].cpu().numpy() obs, reward, termination, truncation, info = test_env.step(action) ep_ret += reward if termination or truncation: successes.append(info["success"]) ep_rets.append(ep_ret) print(ep_ret, successes[-1]) # resets obs, _ = test_env.reset() ep_ret = 0 break print(f"\nTEST: ep_ret={np.mean(ep_rets)}, success={np.mean(successes)}\n") return successes if __name__ == "__main__": args = parse_args() method, seed, train_task = parse_load_name(args.load) task_id = args.task_id if args.task_id is not None else train_task seed = args.seed if args.seed is not None else seed print( f"Method: {method}, seed: {seed}, train task: {train_task}, test task: {task_id}" ) envs = gym.vector.SyncVectorEnv([make_env(task_id, render_human=args.render)]) env = envs.envs[0] # set the seed random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.backends.cudnn.deterministic = True device = torch.device("cuda" if torch.cuda.is_available() else "cpu") if method in ["simple", "finetune"]: model = SimpleAgent.load(args.load, map_location=device) agent = Actor(envs, model) successes = eval_agent(agent, env, num_evals=args.num_episodes, device=device) if args.csv: exists = os.path.exists(args.csv) with open(args.csv, "w" if not exists else "a") as f: if not exists: f.write("algorithm,test task,train task,seed,success\n") for v in successes: f.write(f"{method},{task_id},{train_task},{seed},{v}\n")
3,289
Python
.py
85
31.552941
89
0.62618
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,752
benchmarking.py
mikelma_componet/experiments/meta-world/benchmarking.py
import torch import torch.nn as nn from models.prognet import ProgressiveNet import sys, os sys.path.append(os.path.dirname(__file__) + "/../..") from componet import CompoNet, FirstModuleWrapper import torch.utils.benchmark as benchmark import pandas as pd import argparse def parse_args(): # fmt: off parser = argparse.ArgumentParser() parser.add_argument("--obs-dim", type=int, default=64) parser.add_argument("--act-dim", type=int, default=8) parser.add_argument("--hidden-dim", type=int, default=256) parser.add_argument("--batch-size", type=int, default=8) parser.add_argument("--test-prevs", type=int, default=[5, 10, 20], nargs="+") parser.add_argument("--min-run-time", type=int, default=5) parser.add_argument("--save-path", type=str, default="data/benchmarking.csv") parser.add_argument("--plot", type=bool, default=False, action=argparse.BooleanOptionalAction, help="don't run the benchmark and plot the results from `--save-path`") parser.add_argument("--joined", type=bool, default=False, action=argparse.BooleanOptionalAction, help="whether to plot the ") # fmt: on return parser.parse_args() def build_prognet(obs_dim, act_dim, hidden_dim, num_prevs, device): assert num_prevs > 1 m1 = ProgressiveNet(input_dim=obs_dim, hidden_dim=hidden_dim, previous_models=[]) prevs = [m1] for _ in range(num_prevs): model = ProgressiveNet( input_dim=obs_dim, hidden_dim=hidden_dim, previous_models=prevs.copy() ).to(device) prevs.append(model) model = nn.Sequential(model, nn.Linear(hidden_dim, act_dim)).to(device) return model def build_componet(obs_dim, act_dim, hidden_dim, num_prevs, device): assert num_prevs > 1 net = lambda input_dim: nn.Sequential( nn.Linear(input_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, act_dim), ).to(device) m1 = FirstModuleWrapper(net(obs_dim), ret_probs=False).to(device) prevs = [m1] for _ in range(num_prevs): model = CompoNet( previous_units=prevs.copy(), input_dim=obs_dim, hidden_dim=hidden_dim, out_dim=act_dim, internal_policy=net(obs_dim + hidden_dim), ret_probs=False, proj_bias=True, ).to(device) prevs.append(model) return model def trainable_params(model): return sum(p.numel() for p in model.parameters() if p.requires_grad) def total_params(model): return sum(p.numel() for p in model.parameters()) def prognet_total_parameters(model): s = sum([total_params(m) for m in model[0].previous_models]) return s + total_params(model) def componet_total_parameters(model): s = sum([total_params(m) for m in model.previous_units]) return s + total_params(model) def plot(df): import matplotlib.pyplot as plt from matplotlib.lines import Line2D import seaborn as sns from utils import plt_style methods = ["CompoNet", "ProgressiveNet"] plt.rcParams.update({"font.size": 14}) fig = plt.figure(figsize=(6, 5)) # fmt: off g = sns.lineplot( data=df, x="num prevs", y="time", hue="method", style="method", markers=True, dashes=False, errorbar="sd", legend=False, hue_order=methods, linewidth=3, markersize=10, ) # fmt: on # legend plt_style.style(fig, legend=False) lines = [Line2D([0], [0], color=c) for c in ["tab:blue", "tab:orange"]] fig.legend( lines, methods, fancybox=False, frameon=False, loc="outside lower center", ncols=2, ) ax = plt.gca() p = 0.15 # % box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * p, box.width, box.height * (1 - p)]) # labels plt.xlabel("Number of tasks") plt.ylabel("Inference time in seconds") plt.savefig("benchmarking_inference_time.pdf") # plt.show() plt.gca() fig = plt.figure(figsize=(6, 5)) # fmt: off g = sns.lineplot( data=df, x="num prevs", y="total parameters", hue="method", style="method", markers=True, dashes=False, errorbar="sd", legend=False, hue_order=methods, linewidth=3, markersize=10, ) g = sns.lineplot( data=df, x="num prevs", y="trainable parameters", hue="method", style="method", markers=True, dashes=False, errorbar="sd", legend=False, hue_order=methods, linewidth=1, markersize=7, linestyle="dashed", ) # fmt: on plt_style.style(fig, legend=False, force_sci_y=True) lines = [Line2D([0], [0], color=c) for c in ["tab:blue", "tab:orange"]] lines += [ Line2D([0], [0], color="black"), Line2D([0], [0], color="black", linestyle="dashed"), ] lbls = methods + ["Total", "Trainable"] lbls = [lbls[i] for i in [0, 2, 1, 3]] lines = [lines[i] for i in [0, 2, 1, 3]] fig.legend( lines, lbls, fancybox=False, frameon=False, loc="outside lower center", ncols=2 ) ax = plt.gca() p = 0.21 # % box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * p, box.width, box.height * (1 - p)]) # labels plt.xlabel("Number of tasks") plt.ylabel("Number of parameters") plt.savefig("benchmarking_num_parameters.pdf") plt.show() def plot_times(df, ax, fig, methods): import matplotlib.pyplot as plt from matplotlib.lines import Line2D import seaborn as sns from utils import plt_style g = sns.lineplot( data=df, x="num prevs", y="time", hue="method", style="method", markers=True, dashes=False, errorbar="sd", legend=False, hue_order=methods, linewidth=3, markersize=10, ax=ax, ) ax.set_xticks(list(df["num prevs"].unique())) # fmt: on plt_style.style(fig, ax=ax, legend=False) # labels ax.set_xlabel("Number of tasks") ax.set_ylabel("Inference time in seconds") def plot_memory(df, ax, fig, methods): import matplotlib.pyplot as plt from matplotlib.lines import Line2D import seaborn as sns from utils import plt_style # fmt: off g = sns.lineplot( data=df, x="num prevs", y="trainable parameters", hue="method", style="method", markers=True, dashes=False, errorbar="sd", legend=False, hue_order=methods, linewidth=1, markersize=7, linestyle="dashed", ax=ax, ) g = sns.lineplot( data=df, x="num prevs", y="total parameters", hue="method", style="method", markers=True, dashes=False, errorbar="sd", legend=False, hue_order=methods, linewidth=3, markersize=10, ax=ax, ) ax.set_xticks(list(df["num prevs"].unique())) # fmt: on plt_style.style(fig, ax=ax, legend=False, force_sci_y=True) ax.set_yscale("log") f = lambda x: x * 4 / 1e6 axis_color = "lightgrey" sa = g.secondary_yaxis("right", functions=(f, f), color="white") sa.tick_params(colors="black", which="both") sa.set_ylabel("Memory in MB", color="black") from matplotlib.ticker import ScalarFormatter sa.yaxis.set_major_formatter(ScalarFormatter()) sa.ticklabel_format(style="sci", axis="y", scilimits=(2, 2)) sa.ticklabel_format(useMathText=True) lines = [ Line2D([0], [0], color="black", linestyle="dashed"), Line2D([0], [0], color="black"), ] lbls = ["Trainable", "Total"] ax.legend(lines, lbls, fancybox=False, frameon=False) # labels ax.set_xlabel("Number of tasks") ax.set_ylabel("Number of parameters (log)") ax.set_ylim(1e5, 1e10) def plot_joined(df): import matplotlib.pyplot as plt from matplotlib.lines import Line2D methods = ["CompoNet", "ProgressiveNet"] plt.rcParams.update({"font.size": 14}) # fmt: off fig, axs = plt.subplots( ncols=2, nrows=1, figsize=(7, 5), layout='constrained', gridspec_kw={'wspace': 0.4, 'hspace': 0.2} ) p = 0.2 ax = axs[0] plot_times(df, ax, fig, methods) box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * p, box.width, box.height * (1 - p)]) ax = axs[1] plot_memory(df, ax, fig, methods) box = ax.get_position() ax.set_position([box.x0, box.y0 + box.height * p, box.width, box.height * (1 - p)]) # main legend (in the bottom of the figure) lines = [Line2D([0], [0], color=c, marker=m, linewidth=3, markersize=10, markeredgecolor="white") for c, m in zip(["tab:blue", "tab:orange"], ["X", "o"])] fig.legend( lines, methods, fancybox=False, frameon=False, loc="outside lower center", ncols=2 ) plt.savefig("benchmarking.pdf", pad_inches=0.02, bbox_inches="tight") plt.show() def plot_separate(df): import matplotlib.pyplot as plt from matplotlib.lines import Line2D methods = ["CompoNet", "ProgressiveNet"] plt.rcParams.update({"font.size": 14}) def make_legend(fig, ax, p=0.2): # shrink box = ax.get_position() ax.set_position( [box.x0, box.y0 + box.height * p, box.width, box.height * (1 - p)] ) # draw legend lines = [ Line2D( [0], [0], color=c, marker=m, linewidth=3, markersize=10, markeredgecolor="white", ) for c, m in zip(["tab:blue", "tab:orange"], ["X", "o"]) ] fig.legend( lines, methods, fancybox=False, frameon=False, loc="outside lower center", ncols=2, ) # Inference time fig = plt.figure(figsize=(7, 5)) ax = plt.gca() plot_times(df, ax, fig, methods) make_legend(fig, ax) plt.savefig("benchmarking_inference_time.pdf", pad_inches=0.02, bbox_inches="tight") plt.show() # Memory cost fig = plt.figure(figsize=(7, 7)) ax = plt.gca() plot_memory(df, ax, fig, methods) make_legend(fig, ax, p=0.1) plt.savefig("benchmarking_memory.pdf", pad_inches=0.02, bbox_inches="tight") plt.show() if __name__ == "__main__": args = parse_args() if args.plot: if args.joined: plot_joined(pd.read_csv(args.save_path)) else: plot_separate(pd.read_csv(args.save_path)) quit() device = "cuda" if torch.cuda.is_available() else "cpu" x = torch.rand((args.batch_size, args.obs_dim)).to(device) dfs = [] for num_prevs in args.test_prevs: print("\n==> Num. prevs.:", num_prevs) prognet = build_prognet( args.obs_dim, args.act_dim, args.hidden_dim, num_prevs, device ) p_trainable = trainable_params(prognet) p_total = prognet_total_parameters(prognet) print(f"ProgressiveNet parameters: {p_total}, trainable: {p_trainable}") t0 = benchmark.Timer( stmt="model(x)", globals={"x": x, "model": prognet}, num_threads=torch.get_num_threads(), description="ProgressiveNet", sub_label=str(num_prevs), ) r = t0.blocked_autorange(min_run_time=args.min_run_time) df = pd.DataFrame( { "time": r.times, "method": "ProgressiveNet", "total parameters": p_total, "trainable parameters": p_trainable, "num prevs": num_prevs, } ) dfs.append(df) compo = build_componet( args.obs_dim, args.act_dim, args.hidden_dim, num_prevs, device ) p_trainable = trainable_params(compo) p_total = componet_total_parameters(compo) print(f"CompoNet parameters: {p_total}, trainable: {p_trainable}") t1 = benchmark.Timer( stmt="model(x)", globals={"x": x, "model": compo}, num_threads=torch.get_num_threads(), description="CompoNet", sub_label=str(num_prevs), ) r = t1.blocked_autorange(min_run_time=args.min_run_time) df = pd.DataFrame( { "time": r.times, "method": "CompoNet", "total parameters": p_total, "trainable parameters": p_trainable, "num prevs": num_prevs, } ) dfs.append(df) df = pd.concat(dfs) df.to_csv(args.save_path)
12,720
Python
.py
355
28.222535
90
0.596793
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,753
run_experiments.py
mikelma_componet/experiments/meta-world/run_experiments.py
import subprocess import argparse import random from tasks import tasks def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( "--algorithm", type=str, choices=[ "simple", "componet", "finetune", "from-scratch", "prognet", "packnet", ], required=True, ) parser.add_argument("--seed", type=int, required=True) parser.add_argument("--no-run", default=False, action="store_true") parser.add_argument("--start-mode", type=int, required=True) return parser.parse_args() args = parse_args() modes = list(range(20)) if args.algorithm != "simple" else list(range(10)) # NOTE: If the algoritm is not `simple`, it always should start from the second task if args.algorithm not in ["simple", "packnet", "prognet"] and args.start_mode == 0: start_mode = 1 else: start_mode = args.start_mode run_name = ( lambda task_id: f"task_{task_id}__{args.algorithm if task_id > 0 or args.algorithm in ['packnet', 'prognet'] else 'simple'}__run_sac__{args.seed}" ) first_idx = modes.index(start_mode) for i, task_id in enumerate(modes[first_idx:]): params = f"--model-type={args.algorithm} --task-id={task_id} --seed={args.seed}" params += f" --save-dir=agents" if first_idx > 0 or i > 0: # multiple previous modules if args.algorithm in ["componet", "prognet"]: params += " --prev-units" for i in modes[: modes.index(task_id)]: params += f" agents/{run_name(i)}" # single previous module elif args.algorithm in ["finetune", "packnet"]: params += f" --prev-units agents/{run_name(task_id-1)}" # Launch experiment cmd = f"python3 run_sac.py {params}" print(cmd) if not args.no_run: res = subprocess.run(cmd.split(" ")) if res.returncode != 0: print(f"*** Process returned code {res.returncode}. Stopping on error.") quit(1)
2,035
Python
.py
54
30.814815
150
0.61128
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,754
simple.py
mikelma_componet/experiments/meta-world/models/simple.py
import torch import torch.nn as nn import os from .shared_arch import shared class SimpleAgent(nn.Module): def __init__(self, obs_dim, act_dim): super().__init__() self.act_dim = act_dim self.obs_dim = obs_dim self.fc = shared(input_dim=obs_dim) # will be created when calling `reset_heads` self.fc_mean = None self.fc_logstd = None self.reset_heads() def reset_heads(self): self.fc_mean = nn.Linear(256, self.act_dim) self.fc_logstd = nn.Linear(256, self.act_dim) def forward(self, x): x = self.fc(x) mean = self.fc_mean(x) log_std = self.fc_logstd(x) return mean, log_std def save(self, dirname): os.makedirs(dirname, exist_ok=True) torch.save(self, f"{dirname}/model.pt") def load(dirname, map_location=None, reset_heads=False): model = torch.load(f"{dirname}/model.pt", map_location=map_location) if reset_heads: model.reset_heads() return model
1,042
Python
.py
30
27.333333
76
0.61255
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,755
prognet.py
mikelma_componet/experiments/meta-world/models/prognet.py
import torch import torch.nn as nn import os class ProgressiveNetAgent(nn.Module): def __init__(self, obs_dim, act_dim, prev_paths=[], map_location=None): super().__init__() self.act_dim = act_dim self.obs_dim = obs_dim if len(prev_paths) > 0: prevs = [ torch.load(f"{p}/prognet.pt", map_location=map_location) for p in prev_paths ] else: prevs = [] self.fc = ProgressiveNet( input_dim=obs_dim, hidden_dim=256, previous_models=prevs, ) # will be created when calling `reset_heads` self.fc_mean = None self.fc_logstd = None self.reset_heads() def reset_heads(self): self.fc_mean = nn.Linear(256, self.act_dim) self.fc_logstd = nn.Linear(256, self.act_dim) def forward(self, x, global_timestep=None): x = self.fc(x) mean = self.fc_mean(x) log_std = self.fc_logstd(x) return mean, log_std def save(self, dirname): os.makedirs(dirname, exist_ok=True) if hasattr(self.fc, "previous_models"): del self.fc.previous_models torch.save(self.fc, f"{dirname}/prognet.pt") torch.save(self.fc_mean, f"{dirname}/fc_mean.pt") torch.save(self.fc_logstd, f"{dirname}/fc_logstd.pt") def load( dirname, obs_dim, act_dim, prev_paths, map_location=None, reset_heads=False ): model = ProgressiveNetAgent(obs_dim, act_dim, prev_paths, map_location) model.fc = torch.load(f"{dirname}/model.pt", map_location=map_location) if reset_heads: return model else: model.fc_mean = torch.load( f"{dirname}/fc_mean.pt", map_location=map_location ) model.fc_logstd = torch.load( f"{dirname}/fc_logstd.pt", map_location=map_location ) return model class ProgressiveNet(nn.Module): def __init__(self, input_dim, hidden_dim, previous_models=[]): super().__init__() n_prev = len(previous_models) self.n_prev = n_prev self.fc1 = nn.Linear(input_dim, hidden_dim) self.fc2 = nn.Linear(hidden_dim, hidden_dim) self.u2 = nn.ModuleList( [nn.Linear(hidden_dim, hidden_dim, bias=False) for _ in range(n_prev)] ) self.a = nn.ReLU() # freeze previous models (columns) for m in previous_models: if hasattr(m, "previous_models"): del m.previous_models m.eval() for param in m.parameters(): param.requires_grad = False self.previous_models = previous_models def forward_first(self, x): fc1 = self.a(self.fc1(x)) out = self.a(self.fc2(fc1)) return out, fc1 def forward_other(self, x, fc1s): fc1 = self.a(self.fc1(x)) assert len(fc1s) == len( self.u2 ), "The number of previous layer outputs does not match the number of adapters" h2 = [u(fc1s[i]) for i, u in enumerate(self.u2)] fc2 = sum([self.fc2(fc1), *h2]) out = self.a(fc2) return out, fc1 def forward(self, x, prev_hs=dict(fc1s=[])): if len(self.previous_models) == 0: return self.forward_first(x)[0] # forward first module _, fc1 = self.forward_first(x) fc1s = [fc1] for model in self.previous_models[1:]: _, fc1 = model.forward_other(x, fc1s) fc1s.append(fc1) out = self.forward_other(x, fc1s)[0] return out
3,657
Python
.py
97
27.989691
87
0.566262
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,756
shared_arch.py
mikelma_componet/experiments/meta-world/models/shared_arch.py
import torch.nn as nn def shared(input_dim): return nn.Sequential( nn.Linear(input_dim, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), )
181
Python
.py
8
16.375
34
0.567251
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,757
__init__.py
mikelma_componet/experiments/meta-world/models/__init__.py
from .shared_arch import shared from .simple import SimpleAgent from .compo import CompoNetAgent from .packnet import PackNetAgent from .prognet import ProgressiveNetAgent
172
Python
.py
5
33.4
40
0.874251
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,758
compo.py
mikelma_componet/experiments/meta-world/models/compo.py
import torch import torch.nn as nn import numpy as np from .shared_arch import shared import sys, os sys.path.append(os.path.dirname(__file__) + "/../../../") from componet import CompoNet, FirstModuleWrapper def net(input_dim, output_dim): return nn.Sequential( nn.Linear(input_dim, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), nn.Linear(256, output_dim), ) def take_first(x): return x[0] class CompoNetAgent(nn.Module): def __init__(self, obs_dim, act_dim, prev_paths, map_location=None): super().__init__() self.net_logstd = net(obs_dim, act_dim) prev_units = [ FirstModuleWrapper( model=torch.load( f"{prev_paths[0]}/model.pt", map_location=map_location ), ret_probs=False, transform_output=take_first, ) ] prev_units += [ torch.load(f"{p}/net_mean.pt", map_location=map_location) for p in prev_paths[1:] ] self.net_mean = CompoNet( previous_units=prev_units, input_dim=obs_dim, hidden_dim=256, out_dim=act_dim, internal_policy=net(obs_dim + 256, act_dim), ret_probs=False, ) def forward(self, x, writer=None, global_step=None): if writer is None or global_step is None: mean = self.net_mean(x)[0] else: mean, _phi, att_in, att_out, int_pol, head_out = self.net_mean( x, return_atts=True, ret_int_pol=True, ret_head_out=True ) # log attention values for i, v in enumerate(att_in.mean(0)[0].detach()): writer.add_scalar(f"charts/att_in_{i}", v.item(), global_step) for i, v in enumerate(att_out.mean(0)[0].detach()): writer.add_scalar(f"charts/att_out_{i}", v.item(), global_step) with torch.no_grad(): dist_out_int_pol = (mean - int_pol).abs().mean().item() dist_out_head_out = (mean - head_out).abs().mean().item() dist_int_pol_head_out = (int_pol - head_out).abs().mean().item() writer.add_scalar( f"charts/dist_out_int_pol", dist_out_int_pol, global_step ) writer.add_scalar( f"charts/dist_out_head_out", dist_out_head_out, global_step ) writer.add_scalar( f"charts/dist_int_pol_head_out", dist_int_pol_head_out, global_step ) logstd = self.net_logstd(x) return mean, logstd def save(self, dirname): os.makedirs(dirname, exist_ok=True) del self.net_mean.previous_units torch.save(self.net_mean, f"{dirname}/net_mean.pt") torch.save(self.net_logstd, f"{dirname}/net_logstd.pt") def load(dirname, obs_dim, act_dim, prev_paths, map_location=None): print("Loading previous:", prevs_paths) model = CompoNetAgent( obs_dim=obs_dim, act_dim=act_dim, prevs_paths=prevs_paths, map_location=map_location, ) model.net_logstd = torch.load( f"{dirname}/net_logstd.pt", map_location=map_location ) net_mean = torch.load(f"{dirname}/net_logstd.pt", map_location=map_location) curr = model.net_mean.state_dict() other = net_mean.state_dict() for k in other: curr[k] = other[k] model.net_mean.load_state_dict(curr) return model
3,639
Python
.py
92
28.576087
87
0.549787
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,759
packnet.py
mikelma_componet/experiments/meta-world/models/packnet.py
import torch import torch.nn as nn import copy import os import numpy as np class PackNetAgent(nn.Module): def __init__(self, obs_dim, act_dim, task_id, total_task_num, device): super().__init__() shared = nn.Sequential( nn.Linear(obs_dim, 256), nn.ReLU(), nn.Linear(256, 256), nn.ReLU(), ) self.network = PackNet( model=shared, task_id=task_id + 1, total_task_num=total_task_num, is_first_task=task_id == 0, device=device, ) self.num_actions = act_dim self.fc_mean = nn.Linear(256, act_dim) self.fc_logstd = nn.Linear(256, act_dim) self.retrain_mode = False def forward(self, x): h = self.network(x) mean = self.fc_mean(h) log_std = self.fc_logstd(h) return mean, log_std def save(self, dirname): # un-do the masking for the current task self.network.set_view(None) os.makedirs(dirname, exist_ok=True) torch.save(self, f"{dirname}/packnet.pt") def load( dirname, task_id=None, restart_heads=False, freeze_bias=True, map_location=None ): model = torch.load(f"{dirname}/packnet.pt", map_location=map_location) model.retrain_mode = False if task_id is not None: model.network.task_id = task_id if restart_heads: model.fc_mean = nn.Linear(256, model.num_actions) model.fc_logstd = nn.Linear(256, model.num_actions) if freeze_bias: for name, param in model.network.model.named_parameters(): if name.endswith(".bias"): param.requires_grad = False return model def start_retraining(self): if self.retrain_mode: return # nothing to do print("==> PackNet re-training starts!") self.retrain_mode = True self.network.prune() # generate the masks for the current task self.network.set_view(self.network.task_id) def before_update(self): self.network.adjust_gradients(retrain_mode=self.retrain_mode) class PackNet(nn.Module): def __init__( self, model, task_id, total_task_num, is_first_task, layer_init=lambda x, **kwargs: x, device="cuda" if torch.cuda.is_available() else "cpu", ): super().__init__() assert task_id > 0, "Task ID must be greater than 0 in PackNet" self.model = model self.task_id = task_id self.total_task_num = total_task_num self.prune_percentage = 1 / self.total_task_num self.view = None self.handled_layers = ( [] ) # will contain copies of the original parameters when using views # generate the masks self.masks = [] for name, param in self.model.named_parameters(): if name.endswith(".weight"): self.masks.append( torch.zeros(param.size(), dtype=torch.long, device=device) ) else: self.masks.append(None) # if we're in a tasks that it's not the first, freeze biases if not is_first_task: for name, param in self.model.named_parameters(): if name.endswith(".bias"): param.requires_grad = False @torch.no_grad() def adjust_gradients(self, retrain_mode=False): mask_id = self.task_id if retrain_mode else 0 for p, mask in zip(self.model.parameters(), self.masks): if mask is None: continue p.grad = p.grad * (mask == mask_id) @torch.no_grad() def prune(self): for p, mask in zip(self.model.parameters(), self.masks): if mask is None: continue # sort the unassigned weights from lower to higher magnitudes masked = p * (mask == 0) # only select "free" weights flat = masked.flatten() _sorted, indices = torch.sort( flat.abs(), descending=True ) # sort from max to min magnitude n_prune = int( self.prune_percentage * flat.size(0) ) # number of weights to keep in pruning # create the mask mask.flatten()[indices[:n_prune]] = self.task_id def forward(self, x): return self.model(x) @torch.no_grad() def set_view(self, task_id): if task_id is None and self.view is not None: # restore the original state of the model in the free parameters (not masked) for param_copy, param, mask in zip( self.handled_layers, self.model.parameters(), self.masks ): if param_copy is None: continue m = torch.logical_and( mask <= self.view, mask > 0 ) # pruned=0, not-pruned=1 param.data += param_copy.data * torch.logical_not(m) self.handled_layers = [] self.view = task_id return if len(self.handled_layers) == 0: # save a copy of each (parametrized) layer of the model for param, mask in zip(self.model.parameters(), self.masks): if mask is not None: self.handled_layers.append(copy.deepcopy(param)) else: self.handled_layers.append(None) # apply the masks for p, mask in zip(self.model.parameters(), self.masks): if mask is None: continue # set to zero the parameters that are free (have no mask) or whose mask ID is greater than task_id p.data *= torch.logical_and(mask <= task_id, mask > 0) self.view = task_id
5,895
Python
.py
148
28.837838
110
0.561582
mikelma/componet
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,760
02-connect-bot.py
0x26e_MineflayerPython/scripts/02-connect-bot.py
from javascript import require, On, Once, AsyncTask, once, off # Import the javascript libraries mineflayer = require("mineflayer") # Create bot bot_args = {"username": "connect-bot", "host": "localhost", "port": 3000, "version": "1.19.4", "hideErrors": False} bot = mineflayer.createBot(bot_args) # Login event (Logged in) @On(bot, "login") def login(this): bot_socket = bot._client.socket print( f"Logged in to {bot_socket.server if bot_socket.server else bot_socket._host }" ) # Kicked event (Got kicked from server) @On(bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: print(f"Kicked from server: {reason}") else: print(f"Kicked whilst trying to connect: {reason}") # End event (Disconnected from server) @On(bot, "end") def end(this, reason): print(f"Disconnected: {reason}") # Turn off event listeners off(bot, "login", login) off(bot, "kicked", kicked) off(bot, "end", end)
970
Python
.py
28
31
115
0.683476
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,761
06-logger-bot.py
0x26e_MineflayerPython/scripts/06-logger-bot.py
from javascript import require, On, Once, AsyncTask, once, off # Import the javascript libraries mineflayer = require("mineflayer") # Global bot parameters server_host = "localhost" server_port = 3000 reconnect = True class MCBot: def __init__(self, bot_name): self.bot_args = { "host": server_host, "port": server_port, "username": bot_name, "hideErrors": False, } self.reconnect = reconnect self.bot_name = bot_name self.start_bot() # Tags bot username before console messages def log(self, message): print(f"[{self.bot.username}] {message}") # Start mineflayer bot def start_bot(self): self.bot = mineflayer.createBot(self.bot_args) self.start_events() # Attach mineflayer events to bot def start_events(self): # Login event: Triggers on bot login @On(self.bot, "login") def login(this): # Displays which server you are currently connected to self.bot_socket = self.bot._client.socket self.log( f"Logged in to {self.bot_socket.server if self.bot_socket.server else self.bot_socket._host }" ) # Kicked event: Triggers on kick from server @On(self.bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: self.log(f"Kicked whilst trying to connect: {reason}") # Chat event: Triggers on chat message @On(self.bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified=None): if messagePosition == "chat" and "quit" in message: self.reconnect = False this.quit() # End event: Triggers on disconnect from server @On(self.bot, "end") def end(this, reason): self.log(f"Disconnected: {reason}") # Turn off old events off(self.bot, "login", login) off(self.bot, "kicked", kicked) off(self.bot, "messagestr", messagestr) # Reconnect if self.reconnect: self.log(f"Attempting to reconnect") self.start_bot() # Last event listener off(self.bot, "end", end) # Run function that starts the bot(s) bot = MCBot("bot-1") bot_2 = MCBot("bot-2")
2,400
Python
.py
63
28.666667
110
0.592752
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,762
08-chat-bot.py
0x26e_MineflayerPython/scripts/08-chat-bot.py
from javascript import require, On, Once, AsyncTask, once, off from simple_chalk import chalk from random import randint # Import the javascript libraries mineflayer = require("mineflayer") # Global bot parameters server_host = "localhost" server_port = 3000 reconnect = True class MCBot: def __init__(self, bot_name): self.bot_args = { "host": server_host, "port": server_port, "username": bot_name, "hideErrors": False, } self.reconnect = reconnect self.bot_name = bot_name self.start_bot() # Tags bot username before console messages def log(self, message): print(f"[{self.bot.username}] {message}") # Start mineflayer bot def start_bot(self): self.bot = mineflayer.createBot(self.bot_args) self.start_events() # Attach mineflayer events to bot def start_events(self): # Login event: Triggers on bot login @On(self.bot, "login") def login(this): # Displays which server you are currently connected to self.bot_socket = self.bot._client.socket self.log( chalk.green( f"Logged in to {self.bot_socket.server if self.bot_socket.server else self.bot_socket._host }" ) ) # Spawn event: Triggers on bot entity spawn @On(self.bot, "spawn") def spawn(this): self.bot.chat("Hi!") # Kicked event: Triggers on kick from server @On(self.bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: self.log(chalk.redBright(f"Kicked whilst trying to connect: {reason}")) # Chat event: Triggers on chat message @On(self.bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified=None): if messagePosition == "chat": if "quit" in message: self.bot.chat("Goodbye!") self.reconnect = False this.quit() elif "flip a coin" in message: if randint(1, 2) == 1: self.bot.chat("Heads!") else: self.bot.chat("Tails!") elif "roll a dice" in message: self.bot.chat(f"You rolled {randint(1, 6)}") # End event: Triggers on disconnect from server @On(self.bot, "end") def end(this, reason): self.log(chalk.red(f"Disconnected: {reason}")) # Turn off old events off(self.bot, "login", login) off(self.bot, "spawn", spawn) off(self.bot, "kicked", kicked) off(self.bot, "messagestr", messagestr) # Reconnect if self.reconnect: self.log(chalk.cyanBright(f"Attempting to reconnect")) self.start_bot() # Last event listener off(self.bot, "end", end) bot = MCBot("chat-bot")
3,075
Python
.py
79
27.797468
114
0.55914
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,763
13-pathfinder-bot.py
0x26e_MineflayerPython/scripts/13-pathfinder-bot.py
from javascript import require, On, Once, AsyncTask, once, off from simple_chalk import chalk from utils.vec3_conversion import vec3_to_str # Requires ./utils/vec3_conversion.py # Import the javascript libraries mineflayer = require("mineflayer") mineflayer_pathfinder = require("mineflayer-pathfinder") vec3 = require("vec3") # Global bot parameters server_host = "localhost" server_port = 3000 reconnect = True class MCBot: def __init__(self, bot_name): self.bot_args = { "host": server_host, "port": server_port, "username": bot_name, "hideErrors": False, } self.reconnect = reconnect self.bot_name = bot_name self.start_bot() # Tags bot username before console messages def log(self, message): print(f"[{self.bot.username}] {message}") # Mineflayer: Pathfind to goal def pathfind_to_goal(self, goal_location): try: self.bot.pathfinder.setGoal( mineflayer_pathfinder.pathfinder.goals.GoalNear( goal_location["x"], goal_location["y"], goal_location["z"], 1 ) ) except Exception as e: self.log(f"Error while trying to run pathfind_to_goal: {e}") # Start mineflayer bot def start_bot(self): self.bot = mineflayer.createBot(self.bot_args) self.bot.loadPlugin(mineflayer_pathfinder.pathfinder) self.start_events() # Attach mineflayer events to bot def start_events(self): # Login event: Triggers on bot login @On(self.bot, "login") def login(this): # Displays which server you are currently connected to self.bot_socket = self.bot._client.socket self.log( chalk.green( f"Logged in to {self.bot_socket.server if self.bot_socket.server else self.bot_socket._host }" ) ) # Spawn event: Triggers on bot entity spawn @On(self.bot, "spawn") def spawn(this): self.bot.chat("Hi!") # Kicked event: Triggers on kick from server @On(self.bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: self.log(chalk.redBright(f"Kicked whilst trying to connect: {reason}")) # Chat event: Triggers on chat message @On(self.bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified=None): if messagePosition == "chat": if "quit" in message: self.bot.chat("Goodbye!") self.reconnect = False this.quit() elif "come to me" in message: # Find all nearby players local_players = self.bot.players # Search for our specific player for el in local_players: player_data = local_players[el] if player_data["uuid"] == sender: vec3_temp = local_players[el].entity.position player_location = vec3( vec3_temp["x"], vec3_temp["y"] + 1, vec3_temp["z"] ) # Feedback if player_location: self.log( chalk.magenta( f"Pathfinding to player at {vec3_to_str(player_location)}" ) ) self.pathfind_to_goal(player_location) else: self.log(f"Player not found.") # End event: Triggers on disconnect from server @On(self.bot, "end") def end(this, reason): self.log(chalk.red(f"Disconnected: {reason}")) # Turn off old events off(self.bot, "login", login) off(self.bot, "spawn", spawn) off(self.bot, "kicked", kicked) off(self.bot, "messagestr", messagestr) # Reconnect if self.reconnect: self.log(chalk.cyanBright(f"Attempting to reconnect")) self.start_bot() # Last event listener off(self.bot, "end", end) # Run function that starts the bot(s) bot = MCBot("pathfinder-bot")
4,454
Python
.py
108
28.296296
114
0.542593
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,764
01-simple-bot.py
0x26e_MineflayerPython/scripts/01-simple-bot.py
from javascript import require, On, Once, AsyncTask, once, off # Import the javascript libraries mineflayer = require("mineflayer") # Create bot with basic parameters bot = mineflayer.createBot( {"username": "simple-bot", "host": "localhost", "port": 3000, "version": "1.19.4", "hideErrors": False} ) # Login event required for bot @On(bot, "login") def login(this): pass
383
Python
.py
11
32.818182
107
0.726287
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,765
11-raycast-bot.py
0x26e_MineflayerPython/scripts/11-raycast-bot.py
from javascript import require, On, Once, AsyncTask, once, off from simple_chalk import chalk from utils.vec3_conversion import vec3_to_str import math # Requires ./utils/vec3_conversion.py # Import the javascript libraries mineflayer = require("mineflayer") vec3 = require("vec3") # Global bot parameters server_host = "localhost" server_port = 3000 reconnect = True class MCBot: def __init__(self, bot_name): self.bot_args = { "host": server_host, "port": server_port, "username": bot_name, "hideErrors": False, } self.reconnect = reconnect self.bot_name = bot_name self.start_bot() # Tags bot username before console messages def log(self, message): print(f"[{self.bot.username}] {message}") # Start mineflayer bot def start_bot(self): self.bot = mineflayer.createBot(self.bot_args) self.start_events() # Attach mineflayer events to bot def start_events(self): # Login event: Triggers on bot login @On(self.bot, "login") def login(this): # Displays which server you are currently connected to self.bot_socket = self.bot._client.socket self.log( chalk.green( f"Logged in to {self.bot_socket.server if self.bot_socket.server else self.bot_socket._host }" ) ) # Spawn event: Triggers on bot entity spawn @On(self.bot, "spawn") def spawn(this): self.bot.chat("Hi!") # Kicked event: Triggers on kick from server @On(self.bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: self.log(chalk.redBright(f"Kicked whilst trying to connect: {reason}")) # Chat event: Triggers on chat message @On(self.bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified=None): if messagePosition == "chat": # Quit the bot if "quit" in ' '.join(message.split()[1:]): self.bot.chat("Goodbye!") self.reconnect = False this.quit() # Look at player elif "look at me" in message: # Find all nearby players local_players = self.bot.players # Search for our specific player for el in local_players: player_data = local_players[el] if player_data["uuid"] == sender: vec3_temp = local_players[el].entity.position player_location = vec3( vec3_temp["x"], vec3_temp["y"] + 1, vec3_temp["z"] ) # Feedback if player_location: self.log(chalk.magenta(vec3_to_str(player_location))) self.bot.lookAt(player_location, True) else: self.log(f"Player not found.") # Look at coords elif "look at coords" in message: # Find all nearby players x, y, z = message.split(" ")[-3:] # Feedback block_vec3 = vec3(x, y, z) self.log(chalk.magenta(vec3_to_str(block_vec3))) self.bot.lookAt(block_vec3, True) # Look in a particular direction elif "look" in message: # Get input direction = message.split()[-1] # Calc yaw/pitch for direction yaw, pitch = 0, 0 if direction == "up": pitch = math.pi / 2 yaw = self.bot.entity.yaw elif direction == "down": pitch = -math.pi / 2 yaw = self.bot.entity.yaw elif direction == "east": yaw = math.pi * 3 / 2 elif direction == "south": yaw = math.pi elif direction == "west": yaw = math.pi / 2 elif direction == "north": pass elif direction == "left": yaw = self.bot.entity.yaw + math.pi / 2 elif direction == "right": yaw = self.bot.entity.yaw - math.pi / 2 elif direction == "back": yaw = self.bot.entity.yaw + math.pi pitch = self.bot.entity.pitch # Feedback self.log( chalk.magenta(f"Looking {direction}: {pitch:.2f}/{yaw:.2f}") ) self.bot.look(yaw, pitch, True) # Say which block the bot is looking at elif "what do you see" in message: block = self.bot.blockAtCursor() if block: self.bot.chat(f"Looking at {block.displayName}") else: self.bot.chat("Looking at air") # End event: Triggers on disconnect from server @On(self.bot, "end") def end(this, reason): self.log(chalk.red(f"Disconnected: {reason}")) # Turn off old events off(self.bot, "login", login) off(self.bot, "spawn", spawn) off(self.bot, "kicked", kicked) off(self.bot, "messagestr", messagestr) # Reconnect if self.reconnect: self.log(chalk.cyanBright(f"Attempting to reconnect")) self.start_bot() # Last event listener off(self.bot, "end", end) # Run function that starts the bot(s) bot = MCBot("raycast-bot")
6,083
Python
.py
142
27.232394
114
0.487896
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,766
10-looker-bot.py
0x26e_MineflayerPython/scripts/10-looker-bot.py
from javascript import require, On, Once, AsyncTask, once, off from simple_chalk import chalk from utils.vec3_conversion import vec3_to_str # Requires ./utils/vec3_conversion.py # Import the javascript libraries mineflayer = require("mineflayer") vec3 = require("vec3") # Global bot parameters server_host = "localhost" server_port = 3000 reconnect = True class MCBot: # Constructor def __init__(self, bot_name): self.bot_args = { "host": server_host, "port": server_port, "username": bot_name, "hideErrors": False, } self.reconnect = reconnect self.bot_name = bot_name self.start_bot() # Tags bot username before console messages def log(self, message): print(f"[{self.bot.username}] {message}") # Start mineflayer bot def start_bot(self): self.bot = mineflayer.createBot(self.bot_args) self.start_events() # Attach mineflayer events to bot def start_events(self): # Login event: Triggers on bot login @On(self.bot, "login") def login(this): # Displays which server you are currently connected to self.bot_socket = self.bot._client.socket self.log( chalk.green( f"Logged in to {self.bot_socket.server if self.bot_socket.server else self.bot_socket._host }" ) ) # Spawn event: Triggers on bot entity spawn @On(self.bot, "spawn") def spawn(this): self.bot.chat("Hi!") # Kicked event: Triggers on kick from server @On(self.bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: self.log(chalk.redBright(f"Kicked whilst trying to connect: {reason}")) # Chat event: Triggers on chat message @On(self.bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified=None): if messagePosition == "chat": if "quit" in message: self.bot.chat("Goodbye!") self.reconnect = False this.quit() elif "look at me" in message: # Find all nearby players local_players = self.bot.players # Search for our specific player for el in local_players: player_data = local_players[el] if player_data["uuid"] == sender: vec3_temp = local_players[el].entity.position player_location = vec3( vec3_temp["x"], vec3_temp["y"] + 1, vec3_temp["z"] ) # Feedback if player_location: self.log(chalk.magenta(vec3_to_str(player_location))) self.bot.lookAt(player_location) else: self.log(f"Player not found.") # End event: Triggers on disconnect from server @On(self.bot, "end") def end(this, reason): self.log(chalk.red(f"Disconnected: {reason}")) # Turn off old events off(self.bot, "login", login) off(self.bot, "spawn", spawn) off(self.bot, "kicked", kicked) off(self.bot, "messagestr", messagestr) # Reconnect if self.reconnect: self.log(chalk.cyanBright(f"Attempting to reconnect")) self.start_bot() # Last event listener off(self.bot, "end", end) # Run function that starts the bot(s) bot = MCBot("looker-bot")
3,776
Python
.py
93
28.204301
114
0.546871
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,767
04-reconnect-bot.py
0x26e_MineflayerPython/scripts/04-reconnect-bot.py
from javascript import require, On, Once, AsyncTask, once, off # Import the javascript libraries mineflayer = require("mineflayer") # Create bot bot_args = {"username": "reconnect-bot", "host": "localhost", "port": 3000, "version": "1.19.4", "hideErrors": False} reconnect = True def start_bot(): bot = mineflayer.createBot(bot_args) # Login event (Logged in) @On(bot, "login") def login(this): bot_socket = bot._client.socket print( f"Logged in to {bot_socket.server if bot_socket.server else bot_socket._host }" ) # Kicked event (Got kicked from server) @On(bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: print(f"Kicked whilst trying to connect: {reason}") # Chat event (Received message in chat) @On(bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified): if messagePosition == "chat" and "quit" in message: global reconnect reconnect = False this.quit() # End event (Disconnected from server) @On(bot, "end") def end(this, reason): print(f"Disconnected: {reason}") off(bot, "login", login) off(bot, "kicked", kicked) off(bot, "messagestr", messagestr) if reconnect: print("RESTARTING BOT") start_bot() off(bot, "end", end) # Run function that starts the bot start_bot()
1,463
Python
.py
40
29.725
117
0.627742
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,768
05-multi-bot.py
0x26e_MineflayerPython/scripts/05-multi-bot.py
from javascript import require, On, Once, AsyncTask, once, off # Import the javascript libraries mineflayer = require("mineflayer") # Global bot parameters server_host = "localhost" server_port = 3000 reconnect = True class MCBot: def __init__(self, bot_name): self.bot_args = { "host": server_host, "port": server_port, "username": bot_name, "hideErrors": False, } self.reconnect = reconnect self.bot_name = bot_name self.start_bot() # Start mineflayer bot def start_bot(self): self.bot = mineflayer.createBot(self.bot_args) self.start_events() # Attach mineflayer events to bot def start_events(self): # Login event: Triggers on bot login @On(self.bot, "login") def login(this): # Displays which server you are currently connected to self.bot_socket = self.bot._client.socket print( f"[{self.bot_name}] Logged in to {self.bot_socket.server if self.bot_socket.server else self.bot_socket._host }" ) # Kicked event: Triggers on kick from server @On(self.bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: print(f"[{self.bot_name}] Kicked whilst trying to connect: {reason}") # Chat event: Triggers on chat message @On(self.bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified=None): if messagePosition == "chat" and "quit" in message: self.reconnect = False this.quit() # End event: Triggers on disconnect from server @On(self.bot, "end") def end(this, reason): print(f"[{self.bot_name}] Disconnected: {reason}") # Turn off old events off(self.bot, "login", login) off(self.bot, "kicked", kicked) off(self.bot, "messagestr", messagestr) # Reconnect if self.reconnect: print(f"[{self.bot_name}] Attempting to reconnect") self.start_bot() # Last event listener off(self.bot, "end", end) # Run function that starts the bot(s) bot = MCBot("bot-1") bot_2 = MCBot("bot-2") bot_3 = MCBot("bot-3") bot_4 = MCBot("bot-4") bot_5 = MCBot("bot-5")
2,402
Python
.py
63
28.968254
128
0.589401
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,769
09-eliza-chat-bot.py
0x26e_MineflayerPython/scripts/09-eliza-chat-bot.py
from javascript import require, On, Once, AsyncTask, once, off from simple_chalk import chalk from eliza import eliza # Import the javascript libraries mineflayer = require("mineflayer") # Global bot parameters server_host = "localhost" server_port = 3000 reconnect = True # Setup Eliza chatbot eliza = eliza.Eliza() eliza.load("./eliza/doctor.txt") class MCBot: def __init__(self, bot_name): self.bot_args = { "host": server_host, "port": server_port, "username": bot_name, "hideErrors": False, } self.reconnect = reconnect self.bot_name = bot_name self.start_bot() # Tags bot username before console messages def log(self, message): print(f"[{self.bot.username}] {message}") # Start mineflayer bot def start_bot(self): self.bot = mineflayer.createBot(self.bot_args) self.start_events() # Attach mineflayer events to bot def start_events(self): # Login event: Triggers on bot login @On(self.bot, "login") def login(this): # Displays which server you are currently connected to self.bot_socket = self.bot._client.socket self.log( chalk.green( f"Logged in to {self.bot_socket.server if self.bot_socket.server else self.bot_socket._host }" ) ) # Spawn event: Triggers on bot entity spawn @On(self.bot, "spawn") def spawn(this): self.bot.chat(eliza.initial()) # Kicked event: Triggers on kick from server @On(self.bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: self.log(chalk.redBright(f"Kicked whilst trying to connect: {reason}")) # Chat event: Triggers on chat message @On(self.bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified=None): message_no_tag = " ".join(message.split(" ")[1:]) if messagePosition == "chat" and sender != self.bot.player.uuid: if message_no_tag == "quit": self.bot.chat(eliza.final()) self.reconnect = False this.quit() else: response = eliza.respond(message_no_tag) if response: self.bot.chat(response) else: self.bot.chat("I don't know what to say to that...") # End event: Triggers on disconnect from server @On(self.bot, "end") def end(this, reason): self.log(chalk.red(f"Disconnected: {reason}")) # Turn off old events off(self.bot, "login", login) off(self.bot, "spawn", spawn) off(self.bot, "kicked", kicked) off(self.bot, "messagestr", messagestr) # Reconnect if self.reconnect: self.log(chalk.cyanBright(f"Attempting to reconnect")) self.start_bot() # Last event listener off(self.bot, "end", end) bot = MCBot("AI-chat-bot")
3,213
Python
.py
82
28.463415
114
0.569453
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,770
07-color-bot.py
0x26e_MineflayerPython/scripts/07-color-bot.py
from javascript import require, On, Once, AsyncTask, once, off from simple_chalk import chalk # Import the javascript libraries mineflayer = require("mineflayer") # Global bot parameters server_host = "localhost" server_port = 3000 reconnect = True class MCBot: def __init__(self, bot_name): self.bot_args = { "host": server_host, "port": server_port, "username": bot_name, "hideErrors": False, } self.reconnect = reconnect self.bot_name = bot_name self.start_bot() # Tags bot username before console messages def log(self, message): print(f"[{self.bot.username}] {message}") # Start mineflayer bot def start_bot(self): self.bot = mineflayer.createBot(self.bot_args) self.start_events() # Attach mineflayer events to bot def start_events(self): # Login event: Triggers on bot login @On(self.bot, "login") def login(this): # Displays which server you are currently connected to self.bot_socket = self.bot._client.socket self.log( chalk.green( f"Logged in to {self.bot_socket.server if self.bot_socket.server else self.bot_socket._host }" ) ) # Kicked event: Triggers on kick from server @On(self.bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: self.log(chalk.redBright(f"Kicked whilst trying to connect: {reason}")) # Chat event: Triggers on chat message @On(self.bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified=None): if messagePosition == "chat" and "quit" in message: self.reconnect = False this.quit() # End event: Triggers on disconnect from server @On(self.bot, "end") def end(this, reason): self.log(chalk.red(f"Disconnected: {reason}")) # Turn off old events off(self.bot, "login", login) off(self.bot, "kicked", kicked) off(self.bot, "messagestr", messagestr) # Reconnect if self.reconnect: self.log(chalk.cyanBright(f"Attempting to reconnect")) self.start_bot() # Last event listener off(self.bot, "end", end) # Run function that starts the bot(s) bot = MCBot("color-bot")
2,509
Python
.py
65
28.876923
114
0.59299
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,771
12-jumper-bot.py
0x26e_MineflayerPython/scripts/12-jumper-bot.py
from javascript import require, On, Once, AsyncTask, once, off from simple_chalk import chalk from utils.vec3_conversion import vec3_to_str # Requires ./utils/vec3_to_str.py # Import the javascript libraries mineflayer = require("mineflayer") vec3 = require("vec3") # Global bot parameters server_host = "localhost" server_port = 3000 reconnect = True class MCBot: def __init__(self, bot_name): self.bot_args = { "host": server_host, "port": server_port, "username": bot_name, "hideErrors": False, } self.reconnect = reconnect self.bot_name = bot_name self.start_bot() # Tags bot username before console messages def log(self, message): print(f"[{self.bot.username}] {message}") # Start mineflayer bot def start_bot(self): self.bot = mineflayer.createBot(self.bot_args) self.start_events() # Mineflayer: Run and jump def run_and_jump(self): try: @AsyncTask(start=True) def async_run_and_jump(task): self.bot.setControlState("forward", True) self.bot.waitForTicks(1) self.bot.setControlState("sprint", True) self.bot.setControlState("jump", True) self.bot.waitForTicks(11) self.bot.clearControlStates() except Exception as e: bot.chat(f"Error while trying to run run_and_jump: {e}") # Attach mineflayer events to bot def start_events(self): # Login event: Triggers on bot login @On(self.bot, "login") def login(this): # Displays which server you are currently connected to self.bot_socket = self.bot._client.socket self.log( chalk.green( f"Logged in to {self.bot_socket.server if self.bot_socket.server else self.bot_socket._host }" ) ) # Spawn event: Triggers on bot entity spawn @On(self.bot, "spawn") def spawn(this): self.bot.chat("Hi!") # Kicked event: Triggers on kick from server @On(self.bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: self.log(chalk.redBright(f"Kicked whilst trying to connect: {reason}")) # Chat event: Triggers on chat message @On(self.bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified=None): if messagePosition == "chat": if "quit" in message: self.bot.chat("Goodbye!") self.reconnect = False this.quit() elif "look at me" in message: # Find all nearby players local_players = self.bot.players # Search for our specific player for el in local_players: player_data = local_players[el] if player_data["uuid"] == sender: vec3_temp = local_players[el].entity.position player_location = vec3( vec3_temp["x"], vec3_temp["y"] + 1, vec3_temp["z"] ) # Feedback if player_location: self.log(chalk.magenta(vec3_to_str(player_location))) self.bot.lookAt(player_location) self.run_and_jump() else: self.log(f"Player not found.") # End event: Triggers on disconnect from server @On(self.bot, "end") def end(this, reason): self.log(chalk.red(f"Disconnected: {reason}")) # Turn off old events off(self.bot, "login", login) off(self.bot, "spawn", spawn) off(self.bot, "kicked", kicked) off(self.bot, "messagestr", messagestr) # Reconnect if self.reconnect: self.log(chalk.cyanBright(f"Attempting to reconnect")) self.start_bot() # Last event listener off(self.bot, "end", end) # Run function that starts the bot(s) bot = MCBot("jumper-bot")
4,349
Python
.py
106
28.339623
114
0.545066
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,772
03-disconnect-bot.py
0x26e_MineflayerPython/scripts/03-disconnect-bot.py
from javascript import require, On, Once, AsyncTask, once, off # Import the javascript libraries mineflayer = require("mineflayer") # Create bot bot_args = {"username": "quitting-bot", "host": "localhost", "port": 3000, "version": "1.19.4", "hideErrors": False} bot = mineflayer.createBot(bot_args) # Login event (Logged in) @On(bot, "login") def login(this): bot_socket = bot._client.socket print( f"Logged in to {bot_socket.server if bot_socket.server else bot_socket._host }" ) # Kicked event (Got kicked from server) @On(bot, "kicked") def kicked(this, reason, loggedIn): if loggedIn: print(f"Kicked whilst trying to connect: {reason}") # Chat event (Received message in chat) @On(bot, "messagestr") def messagestr(this, message, messagePosition, jsonMsg, sender, verified): if messagePosition == "chat" and "quit" in message: this.quit() # End event (Disconnected from server) @On(bot, "end") def end(this, reason): print(f"Disconnected: {reason}") # Turn off event listeners off(bot, "login", login) off(bot, "kicked", kicked) off(bot, "end", end) off(bot, "messagestr", messagestr)
1,172
Python
.py
32
33.03125
116
0.695111
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,773
eliza.py
0x26e_MineflayerPython/scripts/eliza/eliza.py
# From https://github.com/wadetb/eliza/blob/master/eliza.py import logging import random import re from collections import namedtuple # Fix Python2/Python3 incompatibility try: input = raw_input except NameError: pass log = logging.getLogger(__name__) class Key: def __init__(self, word, weight, decomps): self.word = word self.weight = weight self.decomps = decomps class Decomp: def __init__(self, parts, save, reasmbs): self.parts = parts self.save = save self.reasmbs = reasmbs self.next_reasmb_index = 0 class Eliza: def __init__(self): self.initials = [] self.finals = [] self.quits = [] self.pres = {} self.posts = {} self.synons = {} self.keys = {} self.memory = [] def load(self, path): key = None decomp = None with open(path) as file: for line in file: if not line.strip(): continue tag, content = [part.strip() for part in line.split(":")] if tag == "initial": self.initials.append(content) elif tag == "final": self.finals.append(content) elif tag == "quit": self.quits.append(content) elif tag == "pre": parts = content.split(" ") self.pres[parts[0]] = parts[1:] elif tag == "post": parts = content.split(" ") self.posts[parts[0]] = parts[1:] elif tag == "synon": parts = content.split(" ") self.synons[parts[0]] = parts elif tag == "key": parts = content.split(" ") word = parts[0] weight = int(parts[1]) if len(parts) > 1 else 1 key = Key(word, weight, []) self.keys[word] = key elif tag == "decomp": parts = content.split(" ") save = False if parts[0] == "$": save = True parts = parts[1:] decomp = Decomp(parts, save, []) key.decomps.append(decomp) elif tag == "reasmb": parts = content.split(" ") decomp.reasmbs.append(parts) def _match_decomp_r(self, parts, words, results): if not parts and not words: return True if not parts or (not words and parts != ["*"]): return False if parts[0] == "*": for index in range(len(words), -1, -1): results.append(words[:index]) if self._match_decomp_r(parts[1:], words[index:], results): return True results.pop() return False elif parts[0].startswith("@"): root = parts[0][1:] if not root in self.synons: raise ValueError("Unknown synonym root {}".format(root)) if not words[0].lower() in self.synons[root]: return False results.append([words[0]]) return self._match_decomp_r(parts[1:], words[1:], results) elif parts[0].lower() != words[0].lower(): return False else: return self._match_decomp_r(parts[1:], words[1:], results) def _match_decomp(self, parts, words): results = [] if self._match_decomp_r(parts, words, results): return results return None def _next_reasmb(self, decomp): index = decomp.next_reasmb_index result = decomp.reasmbs[index % len(decomp.reasmbs)] decomp.next_reasmb_index = index + 1 return result def _reassemble(self, reasmb, results): output = [] for reword in reasmb: if not reword: continue if reword[0] == "(" and reword[-1] == ")": index = int(reword[1:-1]) if index < 1 or index > len(results): raise ValueError("Invalid result index {}".format(index)) insert = results[index - 1] for punct in [",", ".", ";"]: if punct in insert: insert = insert[: insert.index(punct)] output.extend(insert) else: output.append(reword) return output def _sub(self, words, sub): output = [] for word in words: word_lower = word.lower() if word_lower in sub: output.extend(sub[word_lower]) else: output.append(word) return output def _match_key(self, words, key): for decomp in key.decomps: results = self._match_decomp(decomp.parts, words) if results is None: log.debug("Decomp did not match: %s", decomp.parts) continue log.debug("Decomp matched: %s", decomp.parts) log.debug("Decomp results: %s", results) results = [self._sub(words, self.posts) for words in results] log.debug("Decomp results after posts: %s", results) reasmb = self._next_reasmb(decomp) log.debug("Using reassembly: %s", reasmb) if reasmb[0] == "goto": goto_key = reasmb[1] if not goto_key in self.keys: raise ValueError("Invalid goto key {}".format(goto_key)) log.debug("Goto key: %s", goto_key) return self._match_key(words, self.keys[goto_key]) output = self._reassemble(reasmb, results) if decomp.save: self.memory.append(output) log.debug("Saved to memory: %s", output) continue return output return None def respond(self, text): if text.lower() in self.quits: return None text = re.sub(r"\s*\.+\s*", " . ", text) text = re.sub(r"\s*,+\s*", " , ", text) text = re.sub(r"\s*;+\s*", " ; ", text) log.debug("After punctuation cleanup: %s", text) words = [w for w in text.split(" ") if w] log.debug("Input: %s", words) words = self._sub(words, self.pres) log.debug("After pre-substitution: %s", words) keys = [self.keys[w.lower()] for w in words if w.lower() in self.keys] keys = sorted(keys, key=lambda k: -k.weight) log.debug("Sorted keys: %s", [(k.word, k.weight) for k in keys]) output = None for key in keys: output = self._match_key(words, key) if output: log.debug("Output from key: %s", output) break if not output: if self.memory: index = random.randrange(len(self.memory)) output = self.memory.pop(index) log.debug("Output from memory: %s", output) else: output = self._next_reasmb(self.keys["xnone"].decomps[0]) log.debug("Output from xnone: %s", output) return " ".join(output) def initial(self): return random.choice(self.initials) def final(self): return random.choice(self.finals) def run(self): print(self.initial()) while True: sent = input("> ") output = self.respond(sent) if output is None: break print(output) print(self.final()) def main(): eliza = Eliza() eliza.load("doctor.txt") eliza.run() if __name__ == "__main__": logging.basicConfig() main()
7,863
Python
.py
206
25.796117
78
0.500394
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,774
vec3_conversion.py
0x26e_MineflayerPython/scripts/utils/vec3_conversion.py
def vec3_to_str(v): return f"x: {v['x']:.3f}, y: {v['y']:.3f}, z: {v['z']:.3f}" def vec3_to_dict(v): return {"x": v["x"], "y": v["y"], "z": v["z"]}
158
Python
.py
4
36
63
0.421053
0x26e/MineflayerPython
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,775
bbr.py
kalilovers_LightKnightBBR/bbr.py
import os import shutil import platform import subprocess #Colors RED = "\033[91m" GREEN = "\033[92m" YELLOW = "\033[93m" BLUE = "\033[94m" MAGENTA = "\033[95m" CYAN = "\033[96m" RESET = "\033[0m" def show_image(): ascii_art = f""" {MAGENTA}%%%%%%%%%%%%%%%%$%%$%$$$$%%%%%%%%%%%%% %%%%%%%%%%%%%$!!****:!*!*$%$%%%%%%%%%% %%%%%%%%%%%$:%**:*%:!*:::!!%%%%%%%%%%% %%%%%%%%%%*!$*&%$%%@:!!:::!:%$%%%%%%%% %%%%%%%%%!%$*%****$*$$@:::*::!%%%%%%%% %%%%%%%%**%%$::*$:$:*:::::%!::*%%%%%%% %%%%%%%%*:$!%%**%*$:**!*::%*:%:$%%%%%% %%%%%%%%!*$*%!::::!%$$!!::%%:$*$!%%%%% %%%%%%%%:%*%$@:::::$@$@:::$%:$%$!%%%%% %%%%%%%*!*!%::!:::::::*::!*%**$$*%%%%% %%%%%%**!!!*:::::::::%!!!*$$$%%$$$%%%% %%%%%%!*!!:$%*:::::*$!!!%$@%%$%%%$%%%% %%%%%%:!!:%%%%$*%%*%$:::*@@SSSSSSSS%%% %%%%%::!::$$#B%!SS#S::!*S#SSSSSSSSS%%% %%%%%!!!!!**&.&@$@#&!!:!SSBSS$@#SSS%%% %%%%%!!!!!!@#S@&#SS$!!!:S:::#SSSSSS%%% %%%%%!!!*&###$@&SS#S*!!%!!:#SSSSSSS%%% %%%%%!%####@$$SS##S*!!*!%&SSSSSSSSS%%%{RESET} """ print(ascii_art) def show_main_menu(): show_image() print(f"{CYAN}V 1.5{RESET}") print("Special thanks to the Queen") print(f"View the project on GitHub: {BLUE}https://github.com/kalilovers{RESET}") print(f"{BLUE}---------------------------------------------------------{RESET}") print(f"{CYAN}LightKnight{RESET} Script for Qdisc and Congestion Control Setup and Speed Testing ") print("") print(f"0_ {YELLOW}Status{RESET}") print("1_ BBR Base (Recommended)") print("2_ Hybla Base") print("3_ Cubic Base") print("4_ Restore Default Settings") print("5_ Speed Test") print(f"q_ {RED}Exit{RESET}") print("") def show_status_menu(): congestion_control, qdisc_algorithm = get_current_settings() print(f"\n{GREEN}Current Setting:{RESET}") print("") print(f"Current Congestion Control : {GREEN}{congestion_control}{RESET}") print(f"Current Qdisc Algorithm : {GREEN}{qdisc_algorithm}{RESET}") print("\n0: Back") print("") def show_bbr_menu(): print(f"\n{GREEN}BBR Base{RESET}") print("") print("1_BBR + Fq") print("2_BBR + Fq_Codel (Recommended)") print("3_BBR + Cake") print("0_Back") print("") def show_fq_menu(): print(f"\n{GREEN}Apply With Fq{RESET}") print("") print(f"{RED}Warning , Choose carefully :{RESET}") print(f"1_Delete Old File Then Setup+Backup ({GREEN}Recommended for proper optimization{RESET}) ") print(f"2_Setup Without Delete ({YELLOW}If you have special settings in sysctl.conf{RESET})") print("0_Back") print("") def show_fq_codel_menu(): print(f"\n{GREEN}Apply With Fq_Codel{RESET}") print("") print(f"{RED}Warning , Choose carefully :{RESET}") print(f"1_Delete Old File Then Setup+Backup ({GREEN}Recommended for proper optimization{RESET}) ") print(f"2_Setup Without Delete ({YELLOW}If you have special settings in sysctl.conf{RESET})") print("0_Back") print("") def show_cake_menu(): print(f"\n{GREEN}Apply With Cake{RESET}") print("") print(f"{RED}Warning , Choose carefully :{RESET}") print(f"1_Delete Old File Then Setup+Backup ({GREEN}Recommended for proper optimization{RESET}) ") print(f"2_Setup Without Delete ({YELLOW}If you have special settings in sysctl.conf{RESET})") print("0_Back") print("") def show_hybla_menu(): print(f"\n{GREEN}Hybla Base{RESET}") print("") print("1_Hybla + Fq") print("2_Hybla + Fq_Codel") print("3_Hybla + Cake") print("0_Back") print("") def show_cubic_menu(): print(f"\n{GREEN}Cubic Base{RESET}") print("") print("1_Cubic + Fq") print("2_Cubic + Fq_Codel") print("3_Cubic + Cake") print("0_Back") print("") def show_speed_test_menu(): print(f"\n{GREEN}Speed Test{RESET}") print("") print("1_Bench Method1") print("2_Bench Method2") print("3_Iperf3 (Between 2 Server)") print("4_Speedtest Ookla") print("0_Back") print("") def show_iperf_menu(): print(f"\n{GREEN}Choose which one you are:{RESET}") print("") print("1_Client (iran or...)") print("2_Server (Kharej/Target or...)") print("0_Back") print("") def install_required_packages(): print("Checking and installing required packages...") required_packages = ['iproute2', 'iptables'] missing_packages = [] for package in required_packages: result = subprocess.run(['dpkg', '-s', package], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) if result.returncode != 0: missing_packages.append(package) if missing_packages: print(f"The following packages are not installed: {', '.join(missing_packages)}") install_confirm = input("Do you want to install these packages? (y/n): ").strip().lower() if install_confirm in ['y', 'yes']: print(f"Installing: {', '.join(missing_packages)}") subprocess.run(['apt', 'update']) subprocess.run(['apt', 'install', '-y'] + missing_packages) print("Required packages have been installed.") else: print("Installation of required packages was skipped. Exiting the script.") exit(1) else: print("All required packages are installed.") return True def activate_parameters_persistent(): print("Activating parameters persistently...") try: with open("/etc/sysctl.conf", "a") as f: f.write("\n# Enable parameters\n") f.write("net.ipv4.tcp_ecn = 1\n") f.write("net.ipv4.tcp_keepalive_time = 2700\n") f.write("net.ipv4.tcp_keepalive_intvl = 900\n") f.write("net.ipv4.tcp_keepalive_probes = 2\n") f.write("net.ipv4.tcp_sack = 1\n") subprocess.run(['sysctl', '-p']) print("parameters activated and will remain active after reboot.") return True except Exception as e: print(f"parameters activation error: {e}") return False def get_main_interface(): """Find the main interface based on 'UP' status and highest MTU.""" try: interfaces = os.listdir("/sys/class/net/") main_interface = None highest_mtu = -1 virtual_interfaces = ['tun', 'docker', 'veth', 'lo', 'br', 'gre', 'sit', 'vxlan', 'tap', 'gretap', 'ipip'] for interface in interfaces: if any(interface.startswith(v) for v in virtual_interfaces): continue result = subprocess.run(['ip', 'addr', 'show', interface], capture_output=True, text=True) if "UP" in result.stdout: try: with open(f"/sys/class/net/{interface}/mtu", "r") as mtu_file: mtu = int(mtu_file.read().strip()) if mtu > highest_mtu: highest_mtu = mtu main_interface = interface except Exception as e: print(f"Error reading MTU for {interface}: {e}") if main_interface: print(f"Main interface detected: {main_interface} with MTU {highest_mtu}") return main_interface else: print("No main interface found.") return None except Exception as e: print(f"Error detecting main interface: {e}") return None def get_current_settings(): main_interface = get_main_interface() if not main_interface: return "Unknown", "Unknown" try: qdisc_result = subprocess.check_output(f"tc qdisc show dev {main_interface}", shell=True).decode().strip() except subprocess.CalledProcessError: print(f"Error retrieving qdisc for {main_interface}") return "Unknown", "Unknown" qdisc_lines = qdisc_result.splitlines() root_qdisc = None for line in qdisc_lines: if "root" in line: root_qdisc = line.split()[1] break try: congestion_control = subprocess.check_output("sysctl net.ipv4.tcp_congestion_control", shell=True).decode().split('=')[1].strip() except subprocess.CalledProcessError: print("Error retrieving TCP congestion control") congestion_control = "Unknown" return congestion_control, root_qdisc if root_qdisc else "Unknown" def setup_qdisc(algorithm): """Apply the Qdisc to the main interface.""" print("Setting the queuing algorithm on the main network interface...") interface = get_main_interface() if not interface: print("No main network interface found. Exiting script.") return False try: subprocess.run(['tc', 'qdisc', 'replace', 'dev', interface, 'root', algorithm], check=True) print(f"The {algorithm} queuing algorithm was set on the {interface} interface.") return True except subprocess.CalledProcessError as e: print(f"Error in setting the queuing algorithm on {interface}: {e}. Exiting script.") return False def make_qdisc_persistent(algorithm): """Create a systemd service to persist the Qdisc settings after reboot.""" print("Creating systemd service to preserve qdisc settings after reboot on the main interface...") interface = get_main_interface() if not interface: print("No main network interface found. Exiting script.") return False exec_command = f"/sbin/tc qdisc replace dev {interface} root {algorithm}" service_content = f"""[Unit] Description=Set qdisc {algorithm} on the main network interface After=network.target [Service] Type=oneshot ExecStart=/bin/sh -c '{exec_command}' RemainAfterExit=yes [Install] WantedBy=multi-user.target """ service_path = "/etc/systemd/system/qdisc-setup.service" try: with open(service_path, "w") as f: f.write(service_content) subprocess.run(['systemctl', 'daemon-reload']) subprocess.run(['systemctl', 'enable', 'qdisc-setup.service']) subprocess.run(['systemctl', 'start', 'qdisc-setup.service']) print("The systemd service was successfully created and activated for the main interface.") return True except Exception as e: print(f"Error creating systemd service: {e}. Exiting script.") return False def prompt_restart(): while True: try: choice = input(f"\n{GREEN}The mission was successfully completed. Do you want to restart? (Required) Yes or No: {RESET}").strip().lower() if choice in ['n', 'no']: break elif choice in ['y', 'yes']: os.system("reboot") break else: print("Invalid input. Please enter Yes or No.") except UnicodeDecodeError: print("Invalid input. Please use only English characters.") ############################################## For BBR Base def check_kernel_and_os(): print("Checking the compatibility of operating system and kernel...") try: with open("/etc/os-release", "r") as f: lines = f.readlines() distro = "" for line in lines: if line.startswith("ID="): distro = line.strip().split("=")[1].strip('"').lower() break except FileNotFoundError: distro = "" if distro not in ['ubuntu', 'debian']: print("The operating system is not supported. Only Ubuntu and Debian are supported.") return False kernel_version = platform.release() version_numbers = kernel_version.split(".") try: kernel_major = int(version_numbers[0]) kernel_minor = int(version_numbers[1]) except (IndexError, ValueError): print(f"Kernel version {kernel_version} could not be detected.") return False if kernel_major > 4 or (kernel_major == 4 and kernel_minor >= 9): print(f"The kernel version is compatible with BBR.") return True else: print(f"Kernel version {kernel_version} is not supported. Requires version 4.9 or higher.") return False def check_kernel_and_os_cake(): print("Checking the compatibility of operating system and kernel for Cake...") try: with open("/etc/os-release", "r") as f: lines = f.readlines() distro = "" for line in lines: if line.startswith("ID="): distro = line.strip().split("=")[1].strip('"').lower() break except FileNotFoundError: distro = "" if distro not in ['ubuntu', 'debian']: print("The operating system is not supported. Only Ubuntu and Debian are supported.") return False kernel_version = platform.release() version_numbers = kernel_version.split(".") try: kernel_major = int(version_numbers[0]) kernel_minor = int(version_numbers[1]) except (IndexError, ValueError): print(f"Kernel version {kernel_version} could not be detected.") return False if kernel_major > 4 or (kernel_major == 4 and kernel_minor >= 19): print(f"The kernel version is compatible with Cake and BBR.") return True else: print(f"Kernel version {kernel_version} is not supported. Requires version 4.19 or higher.") return False def configure_bbr(algorithm): print("Setting up BBR...") if activate_parameters_persistent(): print("parameters has been activated with BBR.") try: with open("/etc/sysctl.conf", "a") as f: f.write(f"\n# {algorithm} Light Knight\n") f.write(f"net.core.default_qdisc = {algorithm}\n") f.write("net.ipv4.tcp_congestion_control = bbr\n") subprocess.run(['sysctl', '-p']) print("BBR settings applied.") except Exception as e: print(f"Error in setting BBR: {e}") return False if not setup_qdisc(algorithm): return False if not make_qdisc_persistent(algorithm): return False return True def delete_old_file_then_setup(algorithm): print("Deleting old files and setting new (+Backup)...") backup_path = "/etc/sysctl.confback" original_path = "/etc/sysctl.conf" try: if os.path.exists(original_path): shutil.copy(original_path, backup_path) os.remove(original_path) print("The old sysctl.conf file was deleted and backed up.") else: print("No original sysctl.conf file to delete.") except Exception as e: print(f"Error deleting old files: {e}") return False if configure_bbr(algorithm): prompt_restart() else: print("BBR settings encountered a problem.") return True def setup_without_delete(algorithm): print("Setting up without deleting old files...") backup_path = "/etc/sysctl.confback" original_path = "/etc/sysctl.conf" try: if not os.path.exists(backup_path): shutil.copy(original_path, backup_path) print("sysctl.conf file backed up successfully.") except Exception as e: print(f"Error backing up sysctl.conf: {e}") return False if configure_bbr(algorithm): prompt_restart() else: print("BBR settings encountered a problem.") return True ###################### End of BBr based ############################################## For Hybla Base def configure_bbr_hybla(algorithm): print("Setting up hybla...") if activate_parameters_persistent(): print("parameters has been activated with hybla.") try: with open("/etc/sysctl.conf", "a") as f: f.write(f"\n# {algorithm} Light Knight\n") f.write(f"net.core.default_qdisc = {algorithm}\n") f.write("net.ipv4.tcp_congestion_control = hybla\n") subprocess.run(['sysctl', '-p']) print("hybla settings applied.") except Exception as e: print(f"Error in setting hybla: {e}") return False if not setup_qdisc(algorithm): return False if not make_qdisc_persistent(algorithm): return False return True def delete_old_file_then_setup_hybla(algorithm): print("Deleting old files and setting new (+Backup)...") backup_path = "/etc/sysctl.confback" original_path = "/etc/sysctl.conf" try: if os.path.exists(original_path): shutil.copy(original_path, backup_path) os.remove(original_path) print("The old sysctl.conf file was deleted and backed up.") else: print("No original sysctl.conf file to delete.") except Exception as e: print(f"Error deleting old files: {e}") return False if configure_bbr_hybla(algorithm): prompt_restart() else: print("hybla settings encountered a problem.") return True def setup_without_delete_hybla(algorithm): print("Setting up without deleting old files...") backup_path = "/etc/sysctl.confback" original_path = "/etc/sysctl.conf" try: if not os.path.exists(backup_path): shutil.copy(original_path, backup_path) print("sysctl.conf file backed up successfully.") except Exception as e: print(f"Error backing up sysctl.conf: {e}") return False if configure_bbr_hybla(algorithm): prompt_restart() else: print("hybla settings encountered a problem.") return True ###################### End of Hybla based ############################################# For Cubic Base def configure_bbr_cubic(algorithm): print("Setting up Cubic...") if activate_parameters_persistent(): print("parameters has been activated with Cubic.") try: with open("/etc/sysctl.conf", "a") as f: f.write(f"\n# {algorithm} Light Knight\n") f.write(f"net.core.default_qdisc = {algorithm}\n") f.write("net.ipv4.tcp_congestion_control = cubic\n") subprocess.run(['sysctl', '-p']) print("Cubic settings applied.") except Exception as e: print(f"Error in setting Cubic: {e}") return False if not setup_qdisc(algorithm): return False if not make_qdisc_persistent(algorithm): return False return True def delete_old_file_then_setup_cubic(algorithm): print("Deleting old files and setting new (+Backup)...") backup_path = "/etc/sysctl.confback" original_path = "/etc/sysctl.conf" try: if os.path.exists(original_path): shutil.copy(original_path, backup_path) os.remove(original_path) print("The old sysctl.conf file was deleted and backed up.") else: print("No original sysctl.conf file to delete.") except Exception as e: print(f"Error deleting old files: {e}") return False if configure_bbr_cubic(algorithm): prompt_restart() else: print("Cubic settings encountered a problem.") return True def setup_without_delete_cubic(algorithm): print("Setting up without deleting old files...") backup_path = "/etc/sysctl.confback" original_path = "/etc/sysctl.conf" try: if not os.path.exists(backup_path): shutil.copy(original_path, backup_path) print("sysctl.conf file backed up successfully.") except Exception as e: print(f"Error backing up sysctl.conf: {e}") return False if configure_bbr_cubic(algorithm): prompt_restart() else: print("Cubic settings encountered a problem.") return True ###################### End of Cubic based def restore(): print("Restoring default settings...") backup_path = "/etc/sysctl.confback" original_path = "/etc/sysctl.conf" try: if os.path.exists(backup_path): if os.path.exists(original_path): os.remove(original_path) print("Removed the original sysctl.conf file.") shutil.copy(backup_path, original_path) print("Restored sysctl.conf backup.") os.remove(backup_path) print("Backup sysctl.conf file removed.") else: print("No backup found for sysctl.conf.") except Exception as e: print(f"Error restoring sysctl.conf backup: {e}") service_path = "/etc/systemd/system/qdisc-setup.service" try: if os.path.exists(service_path): subprocess.run(['systemctl', 'disable', 'qdisc-setup.service']) os.remove(service_path) subprocess.run(['systemctl', 'daemon-reload']) print("The systemd service related to qdisc was removed.") if os.path.exists("/etc/systemd/system/multi-user.target.wants/qdisc-setup.service"): os.remove("/etc/systemd/system/multi-user.target.wants/qdisc-setup.service") print("Removed /etc/systemd/system/multi-user.target.wants/qdisc-setup.service.") except Exception as e: print(f"Error deleting systemd service: {e}") interface = get_main_interface() if interface: try: subprocess.run(['tc', 'qdisc', 'delete', 'dev', interface, 'root'], check=True) print(f"Default qdisc settings on {interface} were restored.") except subprocess.CalledProcessError: print(f"Default qdisc settings could not be reset on {interface}. Applying fq instead.") subprocess.run(['tc', 'qdisc', 'replace', 'dev', interface, 'root', 'fq'], check=True) print(f"The fq queuing algorithm was set on the {interface} interface.") else: print("No main network interface found to restore settings.") try: subprocess.run(['sysctl', '-p']) print("sysctl settings applied.") except Exception as e: print(f"Error applying sysctl settings: {e}") prompt_restart() return True def run_bench_method1(): print("Running Bench Method1...") os.system("wget -qO- bench.sh | bash") def run_bench_method2(): print("Running Bench Method2...") os.system("curl -Lso- bench.sh | bash") def run_iperf_client(): print("Starting Iperf3 as client...") os.system("apt update") os.system("apt install iperf3 -y") os.system("ufw allow 5201") server_ip = input("What is the IP address of your target server? Enter Your Target IP: ") os.system(f"iperf3 -c {server_ip} -i 1 -t 10 -P 20") input("The download speed test was done. To test the upload speed, press Enter...") os.system(f"iperf3 -c {server_ip} -R -i 1 -t 10 -P 20") input("The upload speed test was done. To Back to the menu, press Enter...") def run_iperf_server(): print("Starting Iperf3 as server...") os.system("apt update") os.system("apt install iperf3 -y") os.system("ufw allow 5201") os.system("iperf3 -s") input("You are active as a server, please do not log out. If it is finished, to Back to the menu, press Enter...") def run_speedtest_ookla(): print("Downloading and running Ookla Speedtest (linux-x86_64) ...") os.system("wget https://install.speedtest.net/app/cli/ookla-speedtest-1.2.0-linux-x86_64.tgz") os.system("tar zxvf ookla-speedtest-1.2.0-linux-x86_64.tgz") server_num = input(f"{GREEN}Enter your{RESET} {YELLOW}ookla-server number{RESET}.{GREEN} Or press Enter to let Speedtest automatically select the closest server: {RESET}") print(f"{CYAN}Speed ​​test starting, please wait...{RESET}") if not server_num: os.system("./speedtest") else: os.system(f"./speedtest -s {server_num}") try: os.remove("ookla-speedtest-1.2.0-linux-x86_64.tgz") if os.path.exists("ookla-speedtest-1.2.0-linux-x86_64"): shutil.rmtree("ookla-speedtest-1.2.0-linux-x86_64") if os.path.exists("./speedtest"): os.remove("./speedtest") for filename in os.listdir("."): if "ookla" in filename or filename.startswith("speedtest"): if os.path.isfile(filename): os.remove(filename) elif os.path.isdir(filename): shutil.rmtree(filename) except Exception as e: print(f"Error cleaning up files: {e}") input(f"{GREEN}SpeedTest Done and files removed, to Back to the menu, press Enter{RESET}") def main(): try: while True: show_main_menu() choice = input("Please enter your choice: ") if choice == '0': while True: show_status_menu() status_choice = input("Please enter your choice (0 to go back): ") if status_choice == '0': break else: print("Invalid choice, please try again.") elif choice == '1': while True: show_bbr_menu() bbr_choice = input("Please enter your choice: ") if bbr_choice == '1': while True: show_fq_menu() fq_choice = input("Please enter your choice: ") if fq_choice == '1': if check_kernel_and_os(): install_required_packages() delete_old_file_then_setup("fq") elif fq_choice == '2': if check_kernel_and_os(): install_required_packages() setup_without_delete("fq") elif fq_choice == '0': break else: print("Invalid choice, please try again.") elif bbr_choice == '2': while True: show_fq_codel_menu() fq_codel_choice = input("Please enter your choice: ") if fq_codel_choice == '1': if check_kernel_and_os(): install_required_packages() delete_old_file_then_setup("fq_codel") elif fq_codel_choice == '2': if check_kernel_and_os(): install_required_packages() setup_without_delete("fq_codel") elif fq_codel_choice == '0': break else: print("Invalid choice, please try again.") elif bbr_choice == '3': while True: show_cake_menu() cake_choice = input("Please enter your choice: ") if cake_choice == '1': if check_kernel_and_os_cake(): install_required_packages() delete_old_file_then_setup("cake") elif cake_choice == '2': if check_kernel_and_os_cake(): install_required_packages() setup_without_delete("cake") elif cake_choice == '0': break else: print("Invalid choice, please try again.") elif bbr_choice == '0': break else: print("Invalid choice, please try again.") elif choice == '2': while True: show_hybla_menu() hybla_choice = input("Please enter your choice: ") if hybla_choice == '1': while True: show_fq_menu() fq_choice = input("Please enter your choice: ") if fq_choice == '1': if check_kernel_and_os(): install_required_packages() delete_old_file_then_setup_hybla("fq") elif fq_choice == '2': if check_kernel_and_os(): install_required_packages() setup_without_delete_hybla("fq") elif fq_choice == '0': break else: print("Invalid choice, please try again.") elif hybla_choice == '2': while True: show_fq_codel_menu() fq_codel_choice = input("Please enter your choice: ") if fq_codel_choice == '1': if check_kernel_and_os(): install_required_packages() delete_old_file_then_setup_hybla("fq_codel") elif fq_codel_choice == '2': if check_kernel_and_os(): install_required_packages() setup_without_delete_hybla("fq_codel") elif fq_codel_choice == '0': break else: print("Invalid choice, please try again.") elif hybla_choice == '3': while True: show_cake_menu() cake_choice = input("Please enter your choice: ") if cake_choice == '1': if check_kernel_and_os_cake(): install_required_packages() delete_old_file_then_setup_hybla("cake") elif cake_choice == '2': if check_kernel_and_os_cake(): install_required_packages() setup_without_delete_hybla("cake") elif cake_choice == '0': break else: print("Invalid choice, please try again.") elif hybla_choice == '0': break else: print("Invalid choice, please try again.") elif choice == '3': while True: show_cubic_menu() cubic_choice = input("Please enter your choice: ") if cubic_choice == '1': while True: show_fq_menu() fq_choice = input("Please enter your choice: ") if fq_choice == '1': if check_kernel_and_os(): install_required_packages() delete_old_file_then_setup_cubic("fq") elif fq_choice == '2': if check_kernel_and_os(): install_required_packages() setup_without_delete_cubic("fq") elif fq_choice == '0': break else: print("Invalid choice, please try again.") elif cubic_choice == '2': while True: show_fq_codel_menu() fq_codel_choice = input("Please enter your choice: ") if fq_codel_choice == '1': if check_kernel_and_os(): install_required_packages() delete_old_file_then_setup_cubic("fq_codel") elif fq_codel_choice == '2': if check_kernel_and_os(): install_required_packages() setup_without_delete_cubic("fq_codel") elif fq_codel_choice == '0': break else: print("Invalid choice, please try again.") elif cubic_choice == '3': while True: show_cake_menu() cake_choice = input("Please enter your choice: ") if cake_choice == '1': if check_kernel_and_os_cake(): install_required_packages() delete_old_file_then_setup_cubic("cake") elif cake_choice == '2': if check_kernel_and_os_cake(): install_required_packages() setup_without_delete_cubic("cake") elif cake_choice == '0': break else: print("Invalid choice, please try again.") elif cubic_choice == '0': break else: print("Invalid choice, please try again.") elif choice == '4': restore() elif choice == '5': while True: show_speed_test_menu() speed_test_choice = input("Please enter your choice: ") if speed_test_choice == '1': run_bench_method1() elif speed_test_choice == '2': run_bench_method2() elif speed_test_choice == '3': while True: show_iperf_menu() iperf_choice = input("Please enter your choice: ") if iperf_choice == '1': run_iperf_client() elif iperf_choice == '2': run_iperf_server() elif iperf_choice == '0': break else: print("Invalid choice, please try again.") elif speed_test_choice == '4': run_speedtest_ookla() elif speed_test_choice == '0': break else: print("Invalid choice, please try again.") elif choice == 'q': print("Goodbye!") break else: print("Invalid choice, please try again.") except KeyboardInterrupt: print("\nExiting...") exit() if __name__ == "__main__": main()
36,457
Python
.py
807
31.203222
176
0.515948
kalilovers/LightKnightBBR
8
4
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,776
cc-spider.py
pisces76_cc-spider/cc-spider.py
import requests from bs4 import BeautifulSoup from docx import Document from docx.shared import Inches from datetime import datetime import os,time #初始化变量 DEBUG = True USER = '葡萄' #配置用户名 SLEEP_TIME = 5 #抓取每篇文章的时间间隔,单位秒 start_page = 874 #起始页面 end_page = 1007 #结束页面 FIXED_URL = 'https://talkcc.org/' #固定URL FILE_NAME = f'./西西河-{USER}-专辑.docx' #生成word文档名 LOG_FILE = f'./cc-spider.log' #生成日志文件名 # 初始化Word文档 if os.path.exists(FILE_NAME): # 文件存在,打开并追加内容 doc = Document(FILE_NAME) doc.add_paragraph('') doc.save(FILE_NAME) else: # 文件不存在,创建新文件 doc = Document() doc.add_heading(f"{USER}文章集合", 0) doc.save(FILE_NAME) def log_message(message): current_time = datetime.now() formatted_time = current_time.strftime("%Y-%m-%d %H:%M:%S ") if DEBUG: print(message) #output to terminal with open(LOG_FILE, 'a') as file: # 将内容追加到文件中 file.write(formatted_time + message + '\n') def http_req(base_url): headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3' } # 设置cookies,注意URL解码 cc_value = 'DcuxFcMgDEXRhVRISF%2BCaTgYmU1SZA%2BXLtNmm3iP0LzqPoSo9uf1fq7P73v3YswnMkaKzTFCQ5srN6CMlrN1CXGDSw0ycaftd%2FdmhFIbFSGmwsR9yEpkRRxTXAXuinPVwzwRNlfnPw%3D%3D' cookies = { 'cc': requests.utils.unquote(cc_value) } # 发送请求并解析网页以获取文章链接 response = requests.get(base_url, headers=headers, cookies=cookies) return response def get_article_links(page_rsp): soup = BeautifulSoup(page_rsp.text, 'html.parser') div_tree = soup.find('div', class_='s_Tree') #format <div class="s_Tree"> all_links = div_tree.find_all('a', href=True) # format: <a href="/article/4487276">xxxx</a> all_dates = div_tree.find_all('small') #format: <small>2020-03-08 12:43:34</small> articles_links = [s for s in all_links if 'article' in str(s)] return all_dates[::-1], articles_links[::-1] #reverse the list for correct order def handle_article(url, date, article_response): article_soup = BeautifulSoup(article_response.text, 'html.parser') #print(article_soup) # 提取文章内容,这里需要根据实际页面结构来调整 sections = article_soup.find(lambda tag: tag.name == 'div' and tag.get('class') == ['s_Sec']) # 精确匹配 <div class="s_Sec"> if sections is None: log_message(f'ERROR: when reading article {url}') return title = sections.find_all('b') p_tags = sections.find_all('p') # 将文章标题和内容添加到Word文档 valid_idx = 1; doc.add_heading(title[valid_idx].get_text(), level=3) doc.add_paragraph(f'原文:{url}') doc.add_paragraph(date) for p_tag in p_tags: if not p_tag.findChildren(): #no subnodes and only string doc.add_paragraph(p_tag) elif p_tag.find('a'): #link h_ref = p_tag.a['href'] doc.add_paragraph(f'{p_tag.a.string} ({h_ref})') elif p_tag.find('img'): #pictures img_element = p_tag.find('img') src_value = img_element['src'] #<img ... src="/picture/0,2405/2256_06203932.png"/> img_path = download_image(FIXED_URL+src_value, './'+src_value) if img_path == None: doc.add_paragraph('missing img src from ' + FIXED_URL + src_value) else: doc.add_picture(img_path, width=Inches(5.5)) else: doc.add_paragraph(p_tag.get_text()) log_message(f"INFO: handle special p_tag = {p_tag}") # 可以选择添加一些分隔符或格式化 doc.add_paragraph('') doc.add_paragraph('') #doc.add_page_break() def download_image(url, file_path): # 兼容Windows/linux风格的路径 file_path = os.path.join(*file_path.split('/')) # 创建目录(如果不存在) os.makedirs(os.path.dirname(file_path), exist_ok=True) response = requests.get(url) if response.status_code == 200: with open(file_path, 'wb') as file: file.write(response.content) log_message(f" Image downloaded and saved as {file_path}") return file_path else: log_message(f"ERROR: Failed to download image from {url}") return None def print_article(date, url): article_response = http_req(url) if (article_response.status_code == 200): handle_article(url, date, article_response) else: log_message(f'ERROR: fail to get article from {url}') # 目标网址 def main(): HOME_PATH = f'{FIXED_URL}user/{USER}/所有帖/' log_message('-----------------------------------------------------------------------------------') log_message(f'Ready to collect {USER}\'s articles from {HOME_PATH}, page {start_page}~{end_page}') start_time = time.time() #record the start time total_articles = 0 #Initialize a couter for total articles for page in range(start_page, end_page+1): log_message(f'Start to process Page-{page}') page_url = f'{HOME_PATH}{page}' page_rsp = http_req(page_url) if (page_rsp.status_code != 200): log_message(f'ERROR: fail to get Page-{page},status_code:{page_rsp.status_code}') continue #page rsp successful dates, articles_links = get_article_links(page_rsp) # 循环处理每个文章链接 for i, link in enumerate(articles_links): article_url = link['href'] if article_url.startswith('/article/'): log_message(f' Start to process {article_url}') url = f'{FIXED_URL}{article_url}' print_article(dates[i], url) total_articles += 1 time.sleep(SLEEP_TIME) doc.save(FILE_NAME) #save for every page #Finally save the file doc.save(FILE_NAME) end_time = time.time() elapsed_time = end_time - start_time hours = int(elapsed_time // 3600) minutes = int((elapsed_time % 3600) // 60) seconds = int(elapsed_time % 60) log_message(f'Done! Total articles downloaded: {total_articles}') log_message(f'Elapsed time: {hours:02d}:{minutes:02d}:{seconds:02d}s') if __name__ == "__main__": if 1: main() else: #test code print_article('', 'https://talkcc.org/article/4108278')
6,857
Python
.py
149
35.885906
167
0.609294
pisces76/cc-spider
8
7
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,777
data_utils.py
Jometeorie_MultiHopShortcuts/code/data_utils.py
import os import json import torch def load_dataset(dataset_path, filename='MQuAKE-CF-3k.json'): with open(os.path.join(dataset_path, filename), 'r') as f: dataset = json.load(f) return dataset def load_prompt(prompt_path, filename): with open(os.path.join(prompt_path, filename), 'r') as f: task_prompt = f.read() return task_prompt def provide_external_prompts(knowledge_list, fewshot_prompt): prompt1 = 'Here are some confirmed facts, don\'t go doubting it.\n' prompt2 = 'Please answer the question based solely on the evidence above.\n' final_prompt = prompt1 for knowlege in knowledge_list: final_prompt += knowlege final_prompt == '\n' return final_prompt + prompt2 + fewshot_prompt # final_prompt = fewshot_prompt # for knowledge in knowledge_list: # final_prompt += '\n' # final_prompt += knowledge # return final_prompt def compute_single_result(data, model, tokenizer, task_prompt, compute_all_single=False, prompt_type='fewshot'): with torch.no_grad(): num_of_old, num_of_new = 0, 0 for multi_hop_question in data['questions']: is_old_answer, is_new_answer = False, False if prompt_type == 'fewshot': multi_hop_question = task_prompt + '\nQ: ' + multi_hop_question + ' A:' elif prompt_type == 'cot': multi_hop_question = task_prompt + '\n\nQuestion: ' + multi_hop_question + ' \nThoughts:' batch = tokenizer([multi_hop_question], return_tensors='pt', padding=True) outputs = model.generate( input_ids=batch['input_ids'].to('cuda'), attention_mask=batch['attention_mask'].to('cuda'), max_new_tokens=10 ) text = tokenizer.decode(outputs[0], skip_special_tokens=True) for ground_truth in data['answer_alias'] + [data['answer']]: if prompt_type == 'fewshot': if ground_truth in text.split(task_prompt)[1].split('A:')[1]: is_old_answer = True elif prompt_type == 'cot': if ground_truth in text.split(task_prompt)[1]: is_old_answer = True for ground_truth in data['new_answer_alias'] + [data['new_answer']]: if prompt_type == 'fewshot': if ground_truth in text.split(task_prompt)[1].split('A:')[1]: is_new_answer = True elif prompt_type == 'cot': if ground_truth in text.split(task_prompt)[1]: is_new_answer = True if is_old_answer: num_of_old += 1 if is_new_answer: num_of_new += 1 if compute_all_single: can_answer_all_single = True for hop in data['new_single_hops']: fewshot_question = task_prompt + '\nQ: ' + hop['question'] + ' A:' batch = tokenizer([fewshot_question], return_tensors='pt', padding=True) outputs = model.generate( input_ids=batch['input_ids'].to('cuda'), attention_mask=batch['attention_mask'].to('cuda'), max_new_tokens=10 ) text = tokenizer.decode(outputs[0], skip_special_tokens=True) single_answer = False for ground_truth in hop['answer_alias'] + [hop['answer']]: # if ground_truth in text.split('Answer: General Motors')[1]: print(text) if ground_truth in text.split(task_prompt)[1].split('A:')[1]: single_answer = True if not single_answer: can_answer_all_single = False return num_of_old, num_of_new, can_answer_all_single else: return num_of_old, num_of_new def compute_sentence_prob(model, tokenizer, input_seq, output_seq_list): total_prob = 0.0 with torch.no_grad(): for output_seq in output_seq_list: input_ids = tokenizer.encode(input_seq, return_tensors='pt').cuda() output_ids = tokenizer.encode(output_seq, return_tensors='pt', add_special_tokens=False)[0] prob = 1.0 for ids in output_ids: logits, past = model(input_ids).values() probs = torch.nn.functional.softmax(logits[:, -1], dim=-1) prob *= probs[0, ids].item() input_ids = torch.cat([input_ids, ids.unsqueeze(0).unsqueeze(0).cuda()], dim=-1) total_prob += prob return total_prob
4,632
Python
.py
94
37.212766
112
0.570635
Jometeorie/MultiHopShortcuts
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,778
erase_with_kn.py
Jometeorie_MultiHopShortcuts/code/erase_with_kn.py
import argparse import os import sys parser = argparse.ArgumentParser() parser.add_argument('--root_path') parser.add_argument('--model_path') args = parser.parse_args() from tqdm import tqdm import copy import collections import numpy as np import torch from transformers import AutoTokenizer, AutoModelForCausalLM from data_utils import load_dataset, load_prompt, compute_single_result, compute_sentence_prob from rome_utils import edit_with_rome from easyeditor.models.kn.knowledge_neurons.knowledge_neurons import KnowledgeNeurons if __name__ == '__main__': dataset = load_dataset(dataset_path=os.path.join(args.root_path, 'MQuAKE/datasets'), filename='MQuAKE-CF-3k.json') fewshot_prompt = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-prompts.txt') cot_prompt = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-cot-prompts.txt') # cot_prompt_tiny = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-cot-prompts_tiny.txt') model = AutoModelForCausalLM.from_pretrained(args.model_path, torch_dtype=torch.float16) tokenizer = AutoTokenizer.from_pretrained(args.model_path) two_hop_dataset = [data for data in dataset if len(data['single_hops']) == 2] # two-hop data only total, num_equals_to_old_answer, num_equals_to_new_answer, num_equals_to_old_answer_after_erase, num_equals_to_new_answer_after_erase = 0, 0, 0, 0, 0 for data in tqdm(two_hop_dataset): # Select the first question for editing only. requested_rewrite = data['requested_rewrite'][0] target_new = requested_rewrite["target_new"]["str"] target_true = requested_rewrite["target_true"]["str"] subject = requested_rewrite["subject"] prompt = f'{requested_rewrite["prompt"].format(subject)}' print(prompt, target_new, subject) model_for_edit = copy.deepcopy(model).cuda() edited_model = edit_with_rome(model_for_edit, tokenizer, [prompt], [target_new], [subject], './hparams/ROME/gpt-j-6B.yaml') is_old_answer, is_new_answer = compute_single_result(data, edited_model, tokenizer, fewshot_prompt) if is_new_answer: num_equals_to_new_answer += 1 elif is_old_answer: num_equals_to_old_answer += 1 total += 1 del edited_model torch.cuda.empty_cache() torch.cuda.empty_cache() torch.cuda.empty_cache() model_for_kn = copy.deepcopy(model).cuda() kn = KnowledgeNeurons(model_for_kn, tokenizer, model_type='gptj', device='cuda:0') # prompts_for_kn = data['questions'] # prompts_for_kn = [fewshot_prompt + '\nQ: ' + multi_hop_question + ' A:' for multi_hop_question in data['questions']] # prompts_for_kn = [cot_prompt_tiny + '\n\nQuestion: ' + multi_hop_question + ' \nThoughts: \nAnswer: ' for multi_hop_question in data['questions']] ground_truth_tok_old = tokenizer.tokenize(data['answer']) ground_truth_tok_new = tokenizer.tokenize(data['new_answer']) all_active_neurons_old = [] all_active_neurons_new = [] neg_neurons = [] for prompt_num in range(3): # fewshot_prompt_tmp = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-prompts_%s.txt' % prompt_num) prompt_for_kn = 'Q: ' + data['questions'][prompt_num] + ' A:' print(tokenizer.tokenize(data['answer'])[0]) all_active_neurons_old.append(kn.get_coarse_neurons(prompt=prompt_for_kn, ground_truth=tokenizer.tokenize(data['answer'])[0], batch_size=5, steps=20, adaptive_threshold=0.3)) # all_active_neurons_new += kn.get_coarse_neurons(prompt=prompt_for_kn, ground_truth=tokenizer.tokenize(data['new_answer']), # batch_size=20, steps=20, adaptive_threshold=0.3) # for i, hop in enumerate(data['single_hops']): # neg_neurons += kn.get_coarse_neurons(prompt=hop['question'], ground_truth=tokenizer.tokenize(hop['answer'])[:1], # batch_size=5, steps=20, adaptive_threshold=0.2) c = collections.Counter() for neurons in all_active_neurons_old: for n in neurons: c[tuple(n)] += 1 muliti_hop_neurons = [list(neuron) for neuron, count in c.items() if count >= 2] # for neuron in neg_neurons: # if neuron in muliti_hop_neurons: # muliti_hop_neurons.remove(neuron) # print('Erasing Knowledge Neurons:', muliti_hop_neurons) # print(len(muliti_hop_neurons)) # for length in range(min(len(ground_truth_tok_old), len(ground_truth_tok_new))): # if ground_truth_tok_old[length] != ground_truth_tok_new[length]: # break # muliti_hop_neurons_answer = kn.get_refined_neurons( # prompts=prompts_for_kn, # # ground_truth=data['answer'], # ground_truth=tokenizer.tokenize(data['answer']), # batch_size=10, # steps=20, # coarse_adaptive_threshold=0.2, # quiet=False # ) # muliti_hop_neurons_new_answer = [] # for prompt_for_kn in prompts_for_kn: # muliti_hop_neurons_new_answer += kn.get_coarse_neurons(prompt=prompt_for_kn, ground_truth=tokenizer.tokenize(data['new_answer']), # batch_size=10, steps=20, adaptive_threshold=0.2) # muliti_hop_neurons = [] # for neuron in muliti_hop_neurons_answer: # if neuron not in muliti_hop_neurons_new_answer: # muliti_hop_neurons.append(neuron) print('Erasing Knowledge Neurons:', muliti_hop_neurons) print(len(muliti_hop_neurons)) kn.erase_knowledge(data['questions'][0], target=data['answer'], neurons=muliti_hop_neurons, undo_modification=False) final_model = edit_with_rome(kn.model, tokenizer, [prompt], [target_new], [subject], './hparams/ROME/gpt-j-6B.yaml') is_old_answer, is_new_answer = compute_single_result(data, final_model, tokenizer, fewshot_prompt) if is_new_answer: num_equals_to_new_answer_after_erase += 1 elif is_old_answer: num_equals_to_old_answer_after_erase += 1 print("Total: %s. Right (old): %s. Right (new): %s." % (total, num_equals_to_old_answer, num_equals_to_new_answer)) print("Right after erasing (old): %s. Right after erasing (new): %s." % (num_equals_to_old_answer_after_erase, num_equals_to_new_answer_after_erase))
6,804
Python
.py
107
55.028037
157
0.635437
Jometeorie/MultiHopShortcuts
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,779
erase_with_rome.py
Jometeorie_MultiHopShortcuts/code/erase_with_rome.py
import argparse import os import sys parser = argparse.ArgumentParser() parser.add_argument('--root_path') parser.add_argument('--model_path') args = parser.parse_args() from tqdm import tqdm import copy import collections import numpy as np import torch from transformers import AutoTokenizer, AutoModelForCausalLM from data_utils import load_dataset, load_prompt, compute_single_result, compute_sentence_prob from rome_utils import edit_with_rome from easyeditor.models.kn.knowledge_neurons.knowledge_neurons import KnowledgeNeurons if __name__ == '__main__': dataset = load_dataset(dataset_path=os.path.join(args.root_path, 'MQuAKE/datasets'), filename='MQuAKE-CF.json') fewshot_prompt = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-prompts.txt') cot_prompt = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-cot-prompts.txt') # cot_prompt_tiny = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-cot-prompts_tiny.txt') model = AutoModelForCausalLM.from_pretrained(args.model_path, torch_dtype=torch.float16) tokenizer = AutoTokenizer.from_pretrained(args.model_path) tokenizer.pad_token_id = tokenizer.eos_token_id two_hop_dataset = [data for data in dataset if len(data['single_hops']) == 2 and data['requested_rewrite'][0]['subject'] in data['questions'][0] and len(data['requested_rewrite']) == 1] # two-hop data only total, num_equals_to_old_answer, num_equals_to_new_answer, num_equals_to_old_answer_after_erase, num_equals_to_new_answer_after_erase = 0, 0, 0, 0, 0 shortcut_idx_list = [] with open('shortcut_idx.txt', 'r') as f: for line in f: shortcut_idx_list.append(int(line.split('\n')[0])) for i, data in tqdm(enumerate(dataset)): if i not in shortcut_idx_list or data['requested_rewrite'][0]['subject'] not in data['questions'][0]: continue # Select the first question for editing only. requested_rewrite = data['requested_rewrite'] model_for_edit = copy.deepcopy(model).cuda() for requested in requested_rewrite: target_new = requested["target_new"]["str"] target_true = requested["target_true"]["str"] subject = requested["subject"] prompt = f'{requested["prompt"].format(subject)}' model_for_edit = edit_with_rome(model_for_edit, tokenizer, [prompt], [target_new], [subject], './hparams/ROME/gpt-j-6B.yaml') is_old_answer, is_new_answer = compute_single_result(data, model_for_edit, tokenizer, fewshot_prompt) if is_new_answer: num_equals_to_new_answer += 1 elif is_old_answer: num_equals_to_old_answer += 1 total += 1 del model_for_edit torch.cuda.empty_cache() torch.cuda.empty_cache() torch.cuda.empty_cache() # prompt_for_rome = [] # for prompt_num in range(3): # fewshot_prompt_tmp = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-prompts.txt') # prompt_for_rome.append(fewshot_prompt_tmp + '\nQ: ' + data['questions'][prompt_num] + ' A:') model_for_rome = copy.deepcopy(model).cuda() prompt_for_rome = ['Q: ' + multi_hop_question + ' A:' for multi_hop_question in data['questions']] final_model = edit_with_rome(model_for_rome, tokenizer, [prompt_for_rome[0]], ['\''], [requested_rewrite[0]['subject']], './hparams/ROME/gpt-j-6B_2.yaml') # prompts_for_kn = data['questions'] # prompts_for_kn = [fewshot_prompt + '\nQ: ' + multi_hop_question + ' A:' for multi_hop_question in data['questions']] # prompts_for_kn = [cot_prompt_tiny + '\n\nQuestion: ' + multi_hop_question + ' \nThoughts: \nAnswer: ' for multi_hop_question in data['questions']] for requested in requested_rewrite: target_new = requested["target_new"]["str"] target_true = requested["target_true"]["str"] subject = requested["subject"] prompt = f'{requested["prompt"].format(subject)}' final_model = edit_with_rome(final_model, tokenizer, [prompt], [target_new], [subject], './hparams/ROME/gpt-j-6B.yaml') is_old_answer, is_new_answer = compute_single_result(data, final_model, tokenizer, fewshot_prompt) if is_new_answer: num_equals_to_new_answer_after_erase += 1 elif is_old_answer: num_equals_to_old_answer_after_erase += 1 print("Total: %s. Right (old): %s. Right (new): %s." % (total, num_equals_to_old_answer, num_equals_to_new_answer)) print("Right after erasing (old): %s. Right after erasing (new): %s." % (num_equals_to_old_answer_after_erase, num_equals_to_new_answer_after_erase))
4,870
Python
.py
75
57.173333
209
0.666527
Jometeorie/MultiHopShortcuts
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,780
compute_neurons.py
Jometeorie_MultiHopShortcuts/code/compute_neurons.py
import argparse import sys parser = argparse.ArgumentParser() parser.add_argument('--root_path') parser.add_argument('--model_path') parser.add_argument('--fact_type') args = parser.parse_args() from tqdm import tqdm import copy import collections import numpy as np import torch from transformers import AutoTokenizer, AutoModelForCausalLM from data_utils import load_dataset, load_prompt, compute_single_result, compute_sentence_prob from rome_utils import edit_with_rome from easyeditor.models.kn.knowledge_neurons.knowledge_neurons import KnowledgeNeurons if __name__ == '__main__': dataset = load_dataset(dataset_path=os.path.join(args.root_path, 'MQuAKE/datasets'), filename='MQuAKE-CF.json') fewshot_prompt = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-prompts-tiny.txt') cot_prompt = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-cot-prompts-tiny.txt') model = AutoModelForCausalLM.from_pretrained(args.model_path, torch_dtype=torch.float16).cuda() tokenizer = AutoTokenizer.from_pretrained(args.model_path) tokenizer.pad_token_id = tokenizer.eos_token_id # two_hop_dataset = [data for data in dataset if len(data['single_hops']) == 2 and data['requested_rewrite'][0]['subject'] in data['questions'][0] and len(data['requested_rewrite']) == 1] # two-hop data only num_of_single_hop_neurons, num_of_fewshot_shared_neurons, num_of_cot_shared_neurons = 0, 0, 0 # shortcut_idx_list = [] # with open('shortcut_idx.txt', 'r') as f: # for line in f: # shortcut_idx_list.append(int(line.split('\n')[0])) for i, data in tqdm(enumerate(dataset)): # if i not in shortcut_idx_list or data['requested_rewrite'][0]['subject'] not in data['questions'][0]: if data['requested_rewrite'][0]['subject'] not in data['questions'][0]: continue # Select the first question for editing only. requested_rewrite = data['requested_rewrite'][0] target_new = requested_rewrite["target_new"]["str"] target_true = requested_rewrite["target_true"]["str"] subject = requested_rewrite["subject"] prompt = f'{requested_rewrite["prompt"].format(subject)}' kn = KnowledgeNeurons(model, tokenizer, model_type='llama', device='cuda:0') single_hop_neurons = [] for hop in data['single_hops']: single_hop_prompt = fewshot_prompt + '\nQ: ' + hop['question'] + ' A:' single_hop_neurons += kn.get_coarse_neurons(prompt=single_hop_prompt, ground_truth=hop['answer'], batch_size=1, steps=20, adaptive_threshold=0.3) multi_hop_fewshot_prompt = fewshot_prompt + '\nQ: ' + data['questions'][0] + ' A:' fewshot_multi_hop_neurons = kn.get_coarse_neurons(prompt=multi_hop_fewshot_prompt, ground_truth=data['answer'], batch_size=1, steps=20, adaptive_threshold=0.3) # cot_muliti_hop_prompt = cot_prompt + '\n\nQuestion: ' + data['questions'][0] + ' \nThoughts: \nAnswer:' # cot_multi_hop_neurons = kn.get_coarse_neurons(prompt=cot_muliti_hop_prompt, ground_truth=data['answer'], # batch_size=1, steps=20, adaptive_threshold=0.3) fewshot_shared_neurons = [] cot_shared_neurons = [] for neuron in single_hop_neurons: if neuron in fewshot_multi_hop_neurons: fewshot_shared_neurons.append(neuron) # if neuron in cot_multi_hop_neurons: # cot_shared_neurons.append(neuron) num_of_single_hop_neurons += len(single_hop_neurons) num_of_fewshot_shared_neurons += len(fewshot_shared_neurons) # num_of_cot_shared_neurons += len(cot_shared_neurons) with open('result_neurons.txt', 'a') as f: f.write('single_hop_neurons: %s, fewshot_multi_hop_neurons: %s, shared_neurons: %s\n' % (len(single_hop_neurons), len(fewshot_multi_hop_neurons), len(fewshot_shared_neurons)))
4,165
Python
.py
63
57.349206
211
0.652536
Jometeorie/MultiHopShortcuts
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,781
record_muliti_fail.py
Jometeorie_MultiHopShortcuts/code/record_muliti_fail.py
import argparse import os import sys parser = argparse.ArgumentParser() parser.add_argument('--root_path') parser.add_argument('--model_path') parser.add_argument('--fact_type') parser.add_argument('--edit_type') args = parser.parse_args() from tqdm import tqdm import copy import collections import numpy as np import torch from transformers import LlamaTokenizer, LlamaForCausalLM from data_utils import load_dataset, load_prompt, compute_single_result, provide_external_prompts, compute_sentence_prob from rome_utils import edit_with_rome, edit_with_memit from easyeditor.models.kn.knowledge_neurons.knowledge_neurons import KnowledgeNeurons if __name__ == '__main__': dataset = load_dataset(dataset_path=os.path.join(args.root_path, 'MQuAKE/datasets'), filename='MQuAKE-CF-3k.json') fewshot_prompt = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-prompts.txt') cot_prompt = load_prompt(prompt_path=os.path.join(args.root_path, 'MQuAKE/prompts'), filename='multihop-cot-prompts.txt') # model = LlamaForCausalLM.from_pretrained(args.model_path, torch_dtype=torch.float16) # tokenizer = LlamaTokenizer.from_pretrained(args.model_path) # model = AutoModelForCausalLM.from_pretrained(args.model_path, torch_dtype=torch.float16) model = LlamaForCausalLM.from_pretrained(args.model_path) # model = AutoModelForCausalLM.from_pretrained(args.model_path) tokenizer = LlamaTokenizer.from_pretrained(args.model_path) tokenizer.pad_token_id = tokenizer.eos_token_id for i, data in tqdm(enumerate(dataset)): requested_rewrite = data['requested_rewrite'] model_for_edit = copy.deepcopy(model).cuda() num_of_old, num_of_new = compute_single_result(data, model_for_edit, tokenizer, fewshot_prompt) # prob_of_old_answer_before_edit = compute_sentence_prob(model_for_edit, tokenizer, fewshot_prompt + '\nQ: ' + data['questions'][0] + ' A:', [data['answer']] + data['answer_alias']) # prob_of_new_answer_before_edit = compute_sentence_prob(model_for_edit, tokenizer, fewshot_prompt + '\nQ: ' + data['questions'][0] + ' A:', [data['new_answer']] + data['new_answer_alias']) knowledge_list = [] for requested in requested_rewrite: target_new = requested["target_new"]["str"] target_true = requested["target_true"]["str"] subject = requested["subject"] prompt = f'{requested["prompt"].format(subject)}' if args.fact_type == 'knowledge_editing': if args.edit_type == 'rome': model_for_edit = edit_with_rome(model_for_edit, tokenizer, [prompt], [target_new], [subject], './hparams/ROME/llama-7b.yaml') elif args.edit_type == 'memit': model_for_edit = edit_with_memit(model_for_edit, tokenizer, [prompt], [target_new], [subject], './hparams/MEMIT/llama-7b.yaml') elif args.fact_type == 'external_knowledge': knowledge_list.append(prompt + ' ' + target_new) # gpt-j-6B.yaml if args.fact_type == 'external_knowledge': fewshot_prompt = provide_external_prompts(knowledge_list, fewshot_prompt) num_of_old_after_edit, num_of_new_after_edit, can_answer_all_single = compute_single_result(data, model_for_edit, tokenizer, fewshot_prompt, compute_all_single=True) # prob_of_old_answer_after_edit = compute_sentence_prob(model_for_edit, tokenizer, fewshot_prompt + '\nQ: ' + data['questions'][0] + ' A:', [data['answer']] + data['answer_alias']) # prob_of_new_answer_after_edit = compute_sentence_prob(model_for_edit, tokenizer, fewshot_prompt + '\nQ: ' + data['questions'][0] + ' A:', [data['new_answer']] + data['new_answer_alias']) if args.fact_type == 'external_knowledge': prefix = 'external_knowledge' else: prefix = 'knowledge_editing' + '_' + args.edit_type with open('results/result_%s.txt' % prefix, 'a') as f: f.write('-----------------------------------------------------------------\n') f.write('Case %s.\n' % i) f.write('Number of old: %s. Num of new: %s. Num of old after edit: %s. Num of new after edit: %s.\n' % (num_of_old, num_of_new, num_of_old_after_edit, num_of_new_after_edit)) # f.write('Prob of old: %s. Prob of new: %s. Prob of old after edit: %s. Prob of new after edit: %s.\n' % (prob_of_old_answer_before_edit, prob_of_new_answer_before_edit, prob_of_old_answer_after_edit, prob_of_new_answer_after_edit)) f.write('Can answer all single hops: %s\n' % str(can_answer_all_single)) f.write(str(data['questions']) + '\n') f.write('Answer: %s.\n' % data['answer']) f.write('New answer: %s.\n' % data['new_answer']) if can_answer_all_single and num_of_old_after_edit > 0: with open('results/shortcut_idx_%s.txt' % prefix, 'a') as f: f.write('%s\n' % i)
5,006
Python
.py
70
63.128571
245
0.652006
Jometeorie/MultiHopShortcuts
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,782
count_paras.py
Jometeorie_MultiHopShortcuts/code/count_paras.py
from datasets import load_dataset import json import time from tqdm import tqdm import re import os import shutil def choose_paras(para_list, length): res = [] for strs in para_list: if len(strs) > length: res.append(strs) return res st = time.time() # ds = load_dataset("wikimedia/wikipedia", "20231101.en") ds = load_dataset("allenai/dolma", split="train", trust_remote_code=True) print(f"time used for data loading: {time.time() - st}") out_dir = "./count_rebuttal" # if os.path.exists(out_dir): # shutil.rmtree(out_dir) if not os.path.exists(out_dir): os.makedirs(out_dir) # text = ds["text"] # print(f"time used for text: {time.time() - st}") # para_list_all = [] # # print(f"len(ds['train']){len(ds['train'])}") # print(f"len(ds['text']:{len(ds['text'])}") # print(f"time used for len: {time.time() - st}") # # for idx in tqdm(range(len(ds['text'][:1000]))): # for idx in tqdm(range(len(ds['text']) // 2)): # content = text[idx] # # print(f"type(content): {type(content)}") # para_list = re.split('\n|\*',content) # para_list = choose_paras(para_list, 100) # para_list_all += para_list # # print(para_list_all[:1000]) # print(f"len(para_list_all): {len(para_list_all)}") # subject = "he" # alias_lst = ["his", "the"] # count = 0 # for paragraph in para_list_all: # flag = False # for alias in alias_lst: # if subject in paragraph and alias in paragraph: # count += 1 # print(f"count: {count}") # print(f"time used: {time.time() - st}") with open("MQuAKE-CF-3k.json", 'r') as f: dict_3K = json.load(f) for sample in dict_3K: idx = sample["case_id"] subject = sample["orig"]["triples_labeled"][0][0].lower() # print(f"subject:{subject}") para_list = [] ori_answer_lst = sample['answer_alias'].copy() ori_answer_lst.append(sample['answer']) for item in ori_answer_lst: para_list.append(item.lower()) txt_path = os.path.join(out_dir, f"{idx}.txt") file = open(txt_path, "a") file.write(f"{idx}\n") file.write(f"{subject}\n") file.write(f"{para_list}\n") file.close() # sample = dict_3K[0] # print(f"ori_answer_lst:{ori_answer_lst}") def counting_para(example): para_list = example["text"].lower().split('\n') # text = example["text"].lower() # text_list = re.split('\n|\*',text) # choosed_text_list = choose_paras(text_list, 20) # print(f"len(choosed_text_list): {len(choosed_text_list)}") for paras in para_list: for sample in dict_3K: subject = sample["orig"]["triples_labeled"][0][0].lower() # print(f"subject: {subject}") # print(f"subject:{subject}") para_list = [] ori_answer_lst = sample['answer_alias'].copy() ori_answer_lst.append(sample['answer']) for item in ori_answer_lst: para_list.append(item.lower()) # txt_path = os.path.join(out_dir, f"{idx}.txt") # print(f"idx:{idx}") for alias in para_list: if subject in paras and alias in paras: count_id = sample["case_id"] # print(f"idx: {count_id}, subject: {subject}, alias: {alias}") with open(os.path.join(out_dir, f"{count_id}.txt"), "a") as f: f.write("appear_once\n") return None ds = ds.map(counting_para, num_proc=256)
3,446
Python
.py
92
32.054348
83
0.594773
Jometeorie/MultiHopShortcuts
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,783
rome_utils.py
Jometeorie_MultiHopShortcuts/code/rome_utils.py
from easyeditor.models.kn.knowledge_neurons.knowledge_neurons import KnowledgeNeurons, model_type from easyeditor import ROMEHyperParams, MEMITHyperParams from easyeditor import BaseEditor def edit_with_rome(model, tokenizer, prompts, target_new, subject, hparams_path): hparams = ROMEHyperParams.from_hparams(hparams_path) editor = BaseEditor.from_hparams(hparams, model=model, tokenizer=tokenizer) metrics, edited_model, _ = editor.edit( prompts=prompts, # ground_truth=ground_truth, target_new=target_new, subject=subject, keep_original_weight=False, verbose=False ) return edited_model def edit_with_memit(model, tokenizer, prompts, target_new, subject, hparams_path): hparams = MEMITHyperParams.from_hparams(hparams_path) editor = BaseEditor.from_hparams(hparams, model=model, tokenizer=tokenizer) metrics, edited_model, _ = editor.edit( prompts=prompts, # ground_truth=ground_truth, target_new=target_new, subject=subject, keep_original_weight=False, verbose=False ) return edited_model
1,132
Python
.py
27
35.777778
97
0.727768
Jometeorie/MultiHopShortcuts
8
1
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,784
rabbit.py
nchanko_myanocr_pub/rabbit.py
# -*- coding: utf-8 -*- # Rabbit-Converter/Rabbit-Python # Zawgyi <-> Unicode converter for Myanmar language import re import sys class Rabbit: @staticmethod def uni2zg(text): rules = [ { "from": u"\u1004\u103a\u1039", "to": u"\u1064" }, { "from": u"\u1039\u1010\u103d", "to": u"\u1096" }, { "from": u"\u1014(?=[\u1030\u103d\u103e\u102f\u1039])", "to": u"\u108f" }, { "from": u"\u102b\u103a", "to": u"\u105a" }, { "from": u"\u100b\u1039\u100c", "to": u"\u1092" }, { "from": u"\u102d\u1036", "to": u"\u108e" }, { "from": u"\u104e\u1004\u103a\u1038", "to": u"\u104e" }, { "from": u"[\u1025\u1009](?=[\u1039\u102f\u1030])", "to": u"\u106a" }, { "from": u"[\u1025\u1009](?=[\u103a])", "to": u"\u1025" }, { "from": u"\u100a(?=[\u1039\u102f\u1030\u103d])", "to": u"\u106b" }, { "from": u"(\u1039[\u1000-\u1021])\u102f", "to": u"\\1\u1033" }, { "from": u"(\u1039[\u1000-\u1021])\u1030", "to": u"\\1\u1034" }, { "from": u"\u1039\u1000", "to": u"\u1060" }, { "from": u"\u1039\u1001", "to": u"\u1061" }, { "from": u"\u1039\u1002", "to": u"\u1062" }, { "from": u"\u1039\u1003", "to": u"\u1063" }, { "from": u"\u1039\u1005", "to": u"\u1065" }, { "from": u"\u1039\u1007", "to": u"\u1068" }, { "from": u"\u1039\u1008", "to": u"\u1069" }, { "from": u"\u100a(?=[\u1039\u102f\u1030])", "to": u"\u106b" }, { "from": u"\u1039\u100b", "to": u"\u106c" }, { "from": u"\u1039\u100c", "to": u"\u106d" }, { "from": u"\u100d\u1039\u100d", "to": u"\u106e" }, { "from": u"\u100e\u1039\u100d", "to": u"\u106f" }, { "from": u"\u1039\u100f", "to": u"\u1070" }, { "from": u"\u1039\u1010", "to": u"\u1071" }, { "from": u"\u1039\u1011", "to": u"\u1073" }, { "from": u"\u1039\u1012", "to": u"\u1075" }, { "from": u"\u1039\u1013", "to": u"\u1076" }, { "from": u"\u1039\u1013", "to": u"\u1076" }, { "from": u"\u1039\u1014", "to": u"\u1077" }, { "from": u"\u1039\u1015", "to": u"\u1078" }, { "from": u"\u1039\u1016", "to": u"\u1079" }, { "from": u"\u1039\u1017", "to": u"\u107a" }, { "from": u"\u1039\u1018", "to": u"\u107b" }, { "from": u"\u1039\u1019", "to": u"\u107c" }, { "from": u"\u1039\u101c", "to": u"\u1085" }, { "from": u"\u103f", "to": u"\u1086" }, { "from": u"(\u103c)\u103e", "to": u"\\1\u1087" }, { "from": u"\u103d\u103e", "to": u"\u108a" }, { "from": u"(\u1064)([\u1031]?)([\u103c]?)([\u1000-\u1021])\u102d", "to": u"\\2\\3\\4\u108b" }, { "from": u"(\u1064)([\u1031]?)([\u103c]?)([\u1000-\u1021])\u102e", "to": u"\\2\\3\\4\u108c" }, { "from": u"(\u1064)([\u1031]?)([\u103c]?)([\u1000-\u1021])\u1036", "to": u"\\2\\3\\4\u108d" }, { "from": u"(\u1064)([\u1031]?)([\u103c]?)([\u1000-\u1021])", "to": u"\\2\\3\\4\\1" }, { "from": u"\u101b(?=[\u102f\u1030\u103d\u108a])", "to": u"\u1090" }, { "from": u"\u100f\u1039\u100d", "to": u"\u1091" }, { "from": u"\u100b\u1039\u100b", "to": u"\u1097" }, { "from": u"([\u1000-\u1021\u1029\u1090])([\u1060-\u1069\u106c\u106d\u1070-\u107c\u1085\u108a])?([\u103b-\u103e]*)?\u1031", "to": u"\u1031\\1\\2\\3" }, { "from": u"([\u1000-\u1021\u1029])([\u1060-\u1069\u106c\u106d\u1070-\u107c\u1085])?(\u103c)", "to": u"\\3\\1\\2" }, { "from": u"\u103a", "to": u"\u1039" }, { "from": u"\u103b", "to": u"\u103a" }, { "from": u"\u103c", "to": u"\u103b" }, { "from": u"\u103d", "to": u"\u103c" }, { "from": u"\u103e", "to": u"\u103d" }, { "from": u"\u103d\u102f", "to": u"\u1088" }, { "from": u"([\u102f\u1030\u1014\u101b\u103c\u108a\u103d\u1088])([\u1032\u1036]{0,1})\u1037", "to": u"\\1\\2\u1095" }, { "from": u"\u102f\u1095", "to": u"\u102f\u1094" }, { "from": u"([\u1014\u101b])([\u1032\u1036\u102d\u102e\u108b\u108c\u108d\u108e])\u1037", "to": u"\\1\\2\u1095" }, { "from": u"\u1095\u1039", "to": u"\u1094\u1039" }, { "from": u"([\u103a\u103b])([\u1000-\u1021])([\u1036\u102d\u102e\u108b\u108c\u108d\u108e]?)\u102f", "to": u"\\1\\2\\3\u1033" }, { "from": u"([\u103a\u103b])([\u1000-\u1021])([\u1036\u102d\u102e\u108b\u108c\u108d\u108e]?)\u1030", "to": u"\\1\\2\\3\u1034" }, { "from": u"\u103a\u102f", "to": u"\u103a\u1033" }, { "from": u"\u103a([\u1036\u102d\u102e\u108b\u108c\u108d\u108e])\u102f", "to": u"\u103a\\1\u1033" }, { "from": u"([\u103a\u103b])([\u1000-\u1021])\u1030", "to": u"\\1\\2\u1034" }, { "from": u"\u103a\u1030", "to": u"\u103a\u1034" }, { "from": u"\u103a([\u1036\u102d\u102e\u108b\u108c\u108d\u108e])\u1030", "to": u"\u103a\\1\u1034" }, { "from": u"\u103d\u1030", "to": u"\u1089" }, { "from": u"\u103b([\u1000\u1003\u1006\u100f\u1010\u1011\u1018\u101a\u101c\u101a\u101e\u101f])", "to": u"\u107e\\1" }, { "from": u"\u107e([\u1000\u1003\u1006\u100f\u1010\u1011\u1018\u101a\u101c\u101a\u101e\u101f])([\u103c\u108a])([\u1032\u1036\u102d\u102e\u108b\u108c\u108d\u108e])", "to": u"\u1084\\1\\2\\3" }, { "from": u"\u107e([\u1000\u1003\u1006\u100f\u1010\u1011\u1018\u101a\u101c\u101a\u101e\u101f])([\u103c\u108a])", "to": u"\u1082\\1\\2" }, { "from": u"\u107e([\u1000\u1003\u1006\u100f\u1010\u1011\u1018\u101a\u101c\u101a\u101e\u101f])([\u1033\u1034]?)([\u1032\u1036\u102d\u102e\u108b\u108c\u108d\u108e])", "to": u"\u1080\\1\\2\\3" }, { "from": u"\u103b([\u1000-\u1021])([\u103c\u108a])([\u1032\u1036\u102d\u102e\u108b\u108c\u108d\u108e])", "to": u"\u1083\\1\\2\\3" }, { "from": u"\u103b([\u1000-\u1021])([\u103c\u108a])", "to": u"\u1081\\1\\2" }, { "from": u"\u103b([\u1000-\u1021])([\u1033\u1034]?)([\u1032\u1036\u102d\u102e\u108b\u108c\u108d\u108e])", "to": u"\u107f\\1\\2\\3" }, { "from": u"\u103a\u103d", "to": u"\u103d\u103a" }, { "from": u"\u103a([\u103c\u108a])", "to": u"\\1\u107d" }, { "from": u"([\u1033\u1034])\u1094", "to": u"\\1\u1095" } ] for rule in rules: text = re.sub(rule["from"], rule["to"], text) return text @staticmethod def zg2uni(text): rules = [ { "from": u"(\u103d|\u1087)", "to": u"\u103e" }, { "from": u"\u103c", "to": u"\u103d" }, { "from": u"(\u103b|\u107e|\u107f|\u1080|\u1081|\u1082|\u1083|\u1084)", "to": u"\u103c" }, { "from": u"(\u103a|\u107d)", "to": u"\u103b" }, { "from": u"\u1039", "to": u"\u103a" }, { "from": u"\u106a", "to": u"\u1009" }, { "from": u"\u106b", "to": u"\u100a" }, { "from": u"\u106c", "to": u"\u1039\u100b" }, { "from": u"\u106d", "to": u"\u1039\u100c" }, { "from": u"\u106e", "to": u"\u100d\u1039\u100d" }, { "from": u"\u106f", "to": u"\u100d\u1039\u100e" }, { "from": u"\u1070", "to": u"\u1039\u100f" }, { "from": u"(\u1071|\u1072)", "to": u"\u1039\u1010" }, { "from": u"\u1060", "to": u"\u1039\u1000" }, { "from": u"\u1061", "to": u"\u1039\u1001" }, { "from": u"\u1062", "to": u"\u1039\u1002" }, { "from": u"\u1063", "to": u"\u1039\u1003" }, { "from": u"\u1065", "to": u"\u1039\u1005" }, { "from": u"\u1068", "to": u"\u1039\u1007" }, { "from": u"\u1069", "to": u"\u1039\u1008" }, { "from": u"/(\u1073|\u1074)/g", "to": u"\u1039\u1011" }, { "from": u"\u1075", "to": u"\u1039\u1012" }, { "from": u"\u1076", "to": u"\u1039\u1013" }, { "from": u"\u1077", "to": u"\u1039\u1014" }, { "from": u"\u1078", "to": u"\u1039\u1015" }, { "from": u"\u1079", "to": u"\u1039\u1016" }, { "from": u"\u107a", "to": u"\u1039\u1017" }, { "from": u"\u107c", "to": u"\u1039\u1019" }, { "from": u"\u1085", "to": u"\u1039\u101c" }, { "from": u"\u1033", "to": u"\u102f" }, { "from": u"\u1034", "to": u"\u1030" }, { "from": u"\u103f", "to": u"\u1030" }, { "from": u"\u1086", "to": u"\u103f" }, { "from": u"\u1036\u1088", "to": u"\u1088\u1036" }, { "from": u"\u1088", "to": u"\u103e\u102f" }, { "from": u"\u1089", "to": u"\u103e\u1030" }, { "from": u"\u108a", "to": u"\u103d\u103e" }, { "from": u"([\u1000-\u1021])\u1064", "to": u"\u1004\u103a\u1039\\1" }, { "from": u"([\u1000-\u1021])\u108b", "to": u"\u1004\u103a\u1039\\1\u102d" }, { "from": u"([\u1000-\u1021])\u108c", "to": u"\u1004\u103a\u1039\\1\u102e" }, { "from": u"([\u1000-\u1021])\u108d", "to": u"\u1004\u103a\u1039\\1\u1036" }, { "from": u"\u108e", "to": u"\u102d\u1036" }, { "from": u"\u108f", "to": u"\u1014" }, { "from": u"\u1090", "to": u"\u101b" }, { "from": u"\u1091", "to": u"\u100f\u1039\u1091" }, { "from": u"\u1019\u102c(\u107b|\u1093)", "to": u"\u1019\u1039\u1018\u102c" }, { "from": u"(\u107b|\u1093)", "to": u"\u103a\u1018" }, { "from": u"(\u1094|\u1095)", "to": u"\u1037" }, { "from": u"\u1096", "to": u"\u1039\u1010\u103d" }, { "from": u"\u1097", "to": u"\u100b\u1039\u100b" }, { "from": u"\u103c([\u1000-\u1021])([\u1000-\u1021])?", "to": u"\\1\u103c\\2" }, { "from": u"([\u1000-\u1021])\u103c\u103a", "to": u"\u103c\\1\u103a" }, { "from": u"\u1031([\u1000-\u1021])(\u103e)?(\u103b)?", "to": u"\\1\\2\\3\u1031" }, { "from": u"([\u1000-\u1021])\u1031([\u103b\u103c\u103d\u103e]+)", "to": u"\\1\\2\u1031" }, { "from": u"\u1032\u103d", "to": u"\u103d\u1032" }, { "from": u"\u103d\u103b", "to": u"\u103b\u103d" }, { "from": u"\u103a\u1037", "to": u"\u1037\u103a" }, { "from": u"\u102f(\u102d|\u102e|\u1036|\u1037)\u102f", "to": u"\u102f\\1" }, { "from": u"\u102f\u102f", "to": u"\u102f" }, { "from": u"(\u102f|\u1030)(\u102d|\u102e)", "to": u"\\2\\1" }, { "from": u"(\u103e)(\u103b|\u1037)", "to": u"\\2\\1" }, { "from": u"\u1025(\u103a|\u102c)", "to": u"\u1009\\1" }, { "from": u"\u1025\u102e", "to": u"\u1026" }, { "from": u"\u1005\u103b", "to": u"\u1008" }, { "from": u"\u1036(\u102f|\u1030)", "to": u"\\1\u1036" }, { "from": u"\u1031\u1037\u103e", "to": u"\u103e\u1031\u1037" }, { "from": u"\u1031\u103e\u102c", "to": u"\u103e\u1031\u102c" }, { "from": u"\u105a", "to": u"\u102b\u103a" }, { "from": u"\u1031\u103b\u103e", "to": u"\u103b\u103e\u1031" }, { "from": u"(\u102d|\u102e)(\u103d|\u103e)", "to": u"\\2\\1" }, { "from": u"\u102c\u1039([\u1000-\u1021])", "to": u"\u1039\\1\u102c" }, { "from": u"\u103c\u1004\u103a\u1039([\u1000-\u1021])", "to": u"\u1004\u103a\u1039\\1\u103c" }, { "from": u"\u1039\u103c\u103a\u1039([\u1000-\u1021])", "to": u"\u103a\u1039\\1\u103c" }, { "from": u"\u103c\u1039([\u1000-\u1021])", "to": u"\u1039\\1\u103c" }, { "from": u"\u1036\u1039([\u1000-\u1021])", "to": u"\u1039\\1\u1036" }, { "from": u"\u1092", "to": u"\u100b\u1039\u100c" }, { "from": u"\u104e", "to": u"\u104e\u1004\u103a\u1038" }, { "from": u"\u1040(\u102b|\u102c|\u1036)", "to": u"\u101d\\1" }, { "from": u"\u1025\u1039", "to": u"\u1009\u1039" }, { "from": u"([\u1000-\u1021])\u103c\u1031\u103d", "to": u"\\1\u103c\u103d\u1031" }, { "from": u"([\u1000-\u1021])\u103d\u1031\u103b", "to": u"\\1\u103b\u103d\u1031" } ] for rule in rules: text = re.sub(rule["from"], rule["to"], text) return text def convert_file(input_file, output_file): try: with open(input_file, 'r', encoding='utf-8') as file: zawgyi_text = file.read() except IOError as e: print(f"Error reading file {input_file}: {e}") return unicode_text = Rabbit.zg2uni(zawgyi_text) try: with open(output_file, 'w', encoding='utf-8') as file: file.write(unicode_text) except IOError as e: print(f"Error writing file {output_file}: {e}") if __name__ == "__main__": if len(sys.argv) < 3: print("Usage: python rabbit.py input_file output_file") sys.exit(1) input_file = sys.argv[1] output_file = sys.argv[2] convert_file(input_file, output_file)
11,078
Python
.py
42
256.761905
5,295
0.540715
nchanko/myanocr_pub
8
2
0
GPL-2.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,785
ocr.py
nchanko_myanocr_pub/ocr.py
import streamlit as st import pytesseract from pdf2image import convert_from_path, pdfinfo_from_path from PIL import Image import tempfile from google.cloud import vision from dotenv import load_dotenv import io import os import shutil service_account_path = 'cloud_vision_service_acc.json' os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = service_account_path # Load environment variables load_dotenv() # Functions for downloading Tesseract data and checking installation from tess_functions import download_tessdata, check_tesseract # Download necessary tessdata files download_tessdata() tessdata_dir = 'tessdata' # Function to find Poppler path def get_poppler_path(): possible_paths = [ '/usr/local/bin', # Common on macOS and some Linux setups '/usr/bin', # Default on many Linux systems '/opt/homebrew/bin', # Homebrew on newer Macs 'C:\\Program Files\\poppler\\bin' # Common on Windows ] for path in possible_paths: if os.path.isfile(os.path.join(path, 'pdftoppm')): return path return None def pdf_to_images(pdf_path, limit=None): poppler_path = get_poppler_path() if not poppler_path: raise FileNotFoundError("Poppler not found. Install it or check your installation.") info = pdfinfo_from_path(pdf_path, userpw=None, poppler_path=poppler_path) max_pages = min(info['Pages'], limit if limit is not None else info['Pages']) max_pages = min(max_pages, 20) # Enforce the maximum limit of 20 pages return convert_from_path(pdf_path, dpi=300, first_page=1, last_page=max_pages, poppler_path=poppler_path) def ocr_with_tesseract(image, languages): lang = "+".join(languages) custom_config = f'--tessdata-dir {tessdata_dir} -l {lang}' return pytesseract.image_to_string(image, config=custom_config) def ocr_with_google(image_path): client = vision.ImageAnnotatorClient() with io.open(image_path, 'rb') as image_file: content = image_file.read() image = vision.Image(content=content) response = client.text_detection(image=image) return response.text_annotations[0].description if response.text_annotations else "" def split_pages(image): # Split the image into two pages width, height = image.size mid_width = width // 2 left_image = image.crop((0, 0, mid_width, height)) right_image = image.crop((mid_width, 0, width, height)) return [left_image, right_image] def main(): st.sidebar.markdown("Developed by [Nyein Chan Ko Ko](https://www.linkedin.com/in/nyeinchankoko/)") st.title(":blue_book: PDF and Image OCR Tool") uploaded_file = st.file_uploader("Upload a PDF or Image file", type=["pdf", "png", "jpg", "jpeg"], help="Upload a pdf or image file") language_mapping = {"English": "eng", "Myanmar": "mya"} available_languages = list(language_mapping.keys()) selected_language_names = st.multiselect("Select OCR Languages", available_languages, default="English", help="Select the language for Tesseract model. If the document contains both English and Myanmar, choose Myanmar first then English.") selected_languages = [language_mapping[name] for name in selected_language_names] ocr_engine = st.selectbox("Select OCR Engine", ["Google OCR", "Tesseract"], help="Select OCR model, Google is better.") page_limit = st.number_input("Limit number of pages to process (set 0 for no limit)", min_value=0, value=10, help="As for trial, Only 10 pages are allowed as maximum. Use these websites to split pdf files. https://smallpdf.com") two_pages_per_scan = st.checkbox("Check if each scan might have two pages side by side", value=False) process_button = st.button("Process PDF", help="Click to process PDF file") cancel_button = st.button("Cancel") if process_button and uploaded_file: with st.spinner('Processing...'): try: # Determine the file type if uploaded_file.type == "application/pdf": with tempfile.TemporaryDirectory() as tmp_dir: tmp_file_path = os.path.join(tmp_dir, "tempfile.pdf") with open(tmp_file_path, 'wb') as f: f.write(uploaded_file.getvalue()) st.success("✅ Loaded PDF file and saved temporarily...") pdf_pages = pdf_to_images(tmp_file_path, limit=page_limit if page_limit > 0 else None) st.success(f"✅ Converted PDF to images, processing {len(pdf_pages)} pages...") all_text = [] progress_bar = st.progress(0) progress_text = st.empty() for i, page in enumerate(pdf_pages): if cancel_button: st.error("Processing cancelled by user.") break if two_pages_per_scan: images_to_process = split_pages(page) else: images_to_process = [page] for split_page in images_to_process: image_path = os.path.join(tmp_dir, f"page_{i + 1}.jpg") split_page.save(image_path, 'JPEG') text = ocr_with_tesseract(Image.open(image_path), selected_languages) if ocr_engine == "Tesseract" else ocr_with_google(image_path) all_text.append(text) # Update progress and display current page processing progress = (i + 1) / len(pdf_pages) progress_bar.progress(progress) progress_text.text(f"Processing page {i + 1}/{len(pdf_pages)}...") st.session_state.ocr_text = "\n".join(all_text) else: with tempfile.NamedTemporaryFile(delete=False, suffix=os.path.splitext(uploaded_file.name)[1]) as tmp_file: tmp_file.write(uploaded_file.getvalue()) st.success("✅ Loaded image and saved temporarily...") if two_pages_per_scan: original_image = Image.open(tmp_file.name) images_to_process = split_pages(original_image) else: images_to_process = [Image.open(tmp_file.name)] all_text = [] for img in images_to_process: text = ocr_with_tesseract(img, selected_languages) if ocr_engine == "Tesseract" else ocr_with_google(tmp_file.name) all_text.append(text) st.session_state.ocr_text = "\n".join(all_text) except Exception as e: if "credential" in str(e).lower(): st.error(f"Credential error: Please check your Google Cloud credentials. Try this instruction to apply Google service acc. https://daminion.net/docs/how-to-get-google-cloud-vision-api-key/") else: st.error(f"An error occurred: {e}") finally: if 'cancel' in st.session_state: del st.session_state['cancel'] if st.session_state.get('ocr_text'): st.text_area("OCR Output", st.session_state.ocr_text, height=250) st.download_button("Download Text", data=st.session_state.ocr_text, file_name="ocr_output.txt", mime="text/plain") if __name__ == "__main__": main()
7,795
Python
.py
130
46.046154
243
0.60512
nchanko/myanocr_pub
8
2
0
GPL-2.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,786
tess_functions.py
nchanko_myanocr_pub/tess_functions.py
import os import requests import pytesseract import streamlit as st def check_tesseract(): tesseract_cmd = tesseract_path() if tesseract_cmd: #st.write(f"Tesseract available at: {tesseract_cmd}") pytesseract.pytesseract.tesseract_cmd = tesseract_cmd else: st.error("Tesseract is not installed or not found in the common paths.") # Find the Tesseract command def tesseract_path(): possible_paths = [ '/usr/bin/tesseract', # Common Linux path '/usr/local/bin/tesseract', # Common alternate path '/opt/homebrew/bin/tesseract', # Homebrew path (macOS) ] for path in possible_paths: if os.path.exists(path): return path return None def download_tessdata(): languages = ['eng', 'mya'] tessdata_dir = 'tessdata' """ Download Tesseract language files if they are not already present in the tessdata directory. :param languages: List of language codes to download, e.g., ['eng', 'osd', 'mya'] :param tessdata_dir: Directory where the Tesseract tessdata files should be stored """ # Ensure the tessdata directory exists os.makedirs(tessdata_dir, exist_ok=True) # GitHub base URL for your tessdata files base_url = "https://raw.githubusercontent.com/nchanko/Myanmar-Ebook-OCR/44c4777dbfcf744390c5081c6341b11499499bf6/Tesseract-OCR/tessdata" # Iterate over each language and download if not exists for lang in languages: lang_file = f"{lang}.traineddata" destination_path = os.path.join(tessdata_dir, lang_file) # Check if the language data file already exists if not os.path.exists(destination_path): # Download the language data file url = f"{base_url}/{lang_file}" try: print(f"Downloading {lang_file}...") response = requests.get(url) response.raise_for_status() # Check if the download was successful # Write the downloaded file to the destination path with open(destination_path, 'wb') as f: f.write(response.content) print(f"Downloaded {lang_file} successfully.") except requests.exceptions.RequestException as e: print(f"Failed to download {lang_file}: {e}")
2,373
Python
.py
52
36.673077
140
0.661817
nchanko/myanocr_pub
8
2
0
GPL-2.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,787
epub_creator.py
nchanko_myanocr_pub/pages/epub_creator.py
import streamlit as st from ebooklib import epub import os def create_epub_with_embedded_font(title, author, text, output_file, font_path, cover_image=None): # Create the book book = epub.EpubBook() # Set metadata book.set_title(title) book.set_language('en') book.add_author(author) if cover_image is not None: # Add cover image from UploadedFile directly book.set_cover("cover.jpg", cover_image.read()) # Create a chapter chapter = epub.EpubHtml(title='Chapter 1', file_name='chapter_1.xhtml', lang='en') chapter.content = f'<html><head><link rel="stylesheet" type="text/css" href="style/style.css"/></head><body><h1>{title}</h1><p>{text}</p></body></html>' book.add_item(chapter) # Embed the custom font font_name = os.path.basename(font_path) font_type = 'application/vnd.ms-opentype' if font_path.endswith('.otf') else 'application/font-woff' book.add_item(epub.EpubItem(uid='font', file_name=f'fonts/{font_name}', media_type=font_type, content=open(font_path, 'rb').read())) # Create the CSS to use the custom font style = f''' @font-face {{ font-family: "CustomFont"; src: url("../fonts/{font_name}"); }} body {{ font-family: "CustomFont"; }} ''' style_item = epub.EpubItem(uid="style", file_name="style/style.css", media_type="text/css", content=style) book.add_item(style_item) # Link the style to the chapter chapter.add_item(style_item) # Add default NCX and Nav files book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) # Define Table Of Contents book.toc = (epub.Link('chapter_1.xhtml', 'Chapter 1', 'chapter_1'),) # Add book spine book.spine = ['nav', chapter] # Create the EPUB file epub.write_epub(output_file, book, {}) def main(): st.title("EPUB Creator") # Create two columns col1, col2 = st.columns(2) with col1: text_file = st.file_uploader("Choose a text file", type=["txt"], help="Upload unicode text file.") title = st.text_input("Title", "My Sample Book") author = st.text_input("Author", "Author Name") with col2: font_options = { "Pyidaungsu": "Pyidaungsu-2.5.3_Regular.ttf", "MUA Office": "MUA_Office_adobe.ttf" # Default font # Add more font options here if needed } font_choice = st.selectbox("Select Font", list(font_options.keys())) font_path = font_options[font_choice] cover_image = st.file_uploader("Choose a cover image", type=["jpg", "jpeg", "png"],help="Upload cover image , this is optional") if st.button("Build EPUB"): if text_file is not None: with st.spinner('Building EPUB...'): text = text_file.read().decode('utf-8') output_file = f"{title}.epub" # Create the EPUB with the custom font create_epub_with_embedded_font(title, author, text, output_file, font_path, cover_image) st.success(f'EPUB file created: {output_file}') # Provide a download link with open(output_file, "rb") as file: btn = st.download_button( label="Download EPUB", data=file, file_name=output_file, mime="application/epub+zip" ) if __name__ == '__main__': main()
3,485
Python
.py
79
35.56962
156
0.606615
nchanko/myanocr_pub
8
2
0
GPL-2.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,788
About.py
nchanko_myanocr_pub/pages/About.py
import streamlit as st def about(): # Read the markdown file st.image("demo.png",caption = "OCR Myanmar Book.",) with open("about.md", "r") as f: markdown_text = f.read() # Display the markdown text on the page st.markdown(markdown_text) about()
278
Python
.py
9
26.333333
55
0.660377
nchanko/myanocr_pub
8
2
0
GPL-2.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,789
font_converter.py
nchanko_myanocr_pub/pages/font_converter.py
import streamlit as st import os from rabbit import Rabbit rabbit = Rabbit() def zawgyi_to_unicode(zawgyi_text): """Convert Zawgyi text to Unicode using the rabbit module.""" return rabbit.zg2uni(zawgyi_text) def convert_file_to_unicode(file): """Read the content of the file, convert it to Unicode, and return the result.""" # Read the content of the file content = file.read() # Decode the content to string if it's in bytes if isinstance(content, bytes): content = content.decode('utf-8') # Convert the text from Zawgyi to Unicode unicode_content = zawgyi_to_unicode(content) return unicode_content def main(): st.sidebar.markdown(""" Credit :[:red[Rabbit Converter]](https://www.rabbit-converter.org/Rabbit/) """) st.title(':blue[Zawgyi to Unicode] Converter') # File uploader allows user to add their own file uploaded_file = st.file_uploader("Choose a file", type=['txt'],help="Select a txt file written in Zawgyi.") if uploaded_file is not None: # Convert the file to Unicode unicode_text = convert_file_to_unicode(uploaded_file) # Show the converted text in a scrollable, full-width text area st.text_area("Converted Text (Unicode):", unicode_text, height=300) # Generate the new file name base_name, ext = os.path.splitext(uploaded_file.name) new_file_name = f"{base_name}_unicode{ext}" # Let user download the converted text st.download_button( label="Download Converted Text", data=unicode_text.encode('utf-8'), file_name=new_file_name, mime='text/plain' ) if __name__ == "__main__": main()
1,741
Python
.py
41
35.634146
111
0.668462
nchanko/myanocr_pub
8
2
0
GPL-2.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,790
crop_pdf.py
nchanko_myanocr_pub/pages/crop_pdf.py
import streamlit as st import fitz # PyMuPDF from PIL import Image import io from pypdf import PdfWriter, PdfReader def load_pdf(pdf_file): """Load the PDF file and return the document object.""" return fitz.open(stream=pdf_file.read(), filetype="pdf") def pdf_page_to_image(pdf_document, page_number, crop_box=None): """Convert a PDF page to an image, optionally cropped.""" page = pdf_document.load_page(page_number) pix = page.get_pixmap() img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) if crop_box: img = img.crop(crop_box) return img def display_sample_pages(pdf_document, start_page, end_page, crop_box=None): """Display a range of pages of the PDF with optional cropping in two columns.""" num_pages = len(pdf_document) end_page = min(end_page, num_pages) # Ensure end_page does not exceed total pages cols = st.columns(2) # Create two columns for i in range(start_page - 1, end_page): # Pages are 0-indexed in PyMuPDF img = pdf_page_to_image(pdf_document, i, crop_box) col = cols[(i - start_page + 1) % 2] with col: st.image(img, caption=f"Page {i + 1}", use_column_width=True) def main(): st.title("PDF Crop Tool") # Organize PDF upload and page range selection into two columns col1, col2 = st.columns(2) with col1: pdf_file = st.file_uploader("Upload PDF", type=["pdf"]) if pdf_file is not None: pdf_document = load_pdf(pdf_file) max_pages = len(pdf_document) with col2: start_page, end_page = st.slider( "Select the page range", min_value=1, max_value=max_pages, value=(1, min(10, max_pages)) ) st.header("Crop Settings") # Organize crop settings into two columns col1, col2 = st.columns(2) with col1: x1 = st.number_input("Crop X1 (left)", min_value=0, max_value=int(pdf_document.load_page(0).rect.width), value=0) y1 = st.number_input("Crop Y1 (top)", min_value=0, max_value=int(pdf_document.load_page(0).rect.height), value=0) with col2: x2 = st.number_input("Crop X2 (right)", min_value=0, max_value=int(pdf_document.load_page(0).rect.width), value=int(pdf_document.load_page(0).rect.width)) y2 = st.number_input("Crop Y2 (bottom)", min_value=0, max_value=int(pdf_document.load_page(0).rect.height), value=int(pdf_document.load_page(0).rect.height)) crop_box = (x1, y1, x2, y2) st.header("Sample Pages (After Cropping)") display_sample_pages(pdf_document, start_page, end_page, crop_box) if st.button("Apply Cropping to PDF"): output_pdf = io.BytesIO() pdf_writer = PdfWriter() for page_num in range(len(pdf_document)): page = pdf_document.load_page(page_num) pix = page.get_pixmap() img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) img = img.crop(crop_box) # Convert cropped image to PDF page img_bytes = io.BytesIO() img.save(img_bytes, format="PDF") img_bytes.seek(0) pdf_reader = PdfReader(img_bytes) pdf_writer.add_page(pdf_reader.pages[0]) pdf_writer.write(output_pdf) output_pdf.seek(0) st.success("PDF Cropping Applied!") st.download_button(label="Download Cropped PDF", data=output_pdf, file_name="cropped_pdf.pdf", mime="application/pdf") if __name__ == "__main__": main()
3,683
Python
.py
74
40.094595
169
0.613274
nchanko/myanocr_pub
8
2
0
GPL-2.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,791
tachibk-converter.py
BrutuZ_tachibk-converter/tachibk-converter.py
import gzip import re import varint from argparse import ArgumentParser from base64 import b64decode, b64encode from json import dumps, loads from pathlib import Path from requests import get from struct import pack, unpack from subprocess import run from google.protobuf.json_format import ( Parse, ParseError, MessageToDict, ) FORKS = { 'mihon': 'mihonapp/mihon', 'sy': 'jobobby04/TachiyomiSY', 'j2k': 'Jays2Kings/tachiyomiJ2K', 'yokai': 'null2264/yokai', } PROTONUMBER_RE = r'(?:^\s*(?!\/\/\s*)@ProtoNumber\((?P<number>\d+)\)\s*|data class \w+\(|^)va[rl]\s+(?P<name>\w+):\s+(?:(?:(?:List|Set)<(?P<list>\w+)>)|(?P<type>\w+))(?P<optional>\?|(:?\s+=))?' CLASS_RE = r'^(?:data )?class (?P<name>\w+)\((?P<defs>(?:[^)(]+|\((?:[^)(]+|\([^)(]*\))*\))*)\)' DATA_TYPES = { 'String': 'string', 'Int': 'int32', 'Long': 'int64', 'Boolean': 'bool', 'Float': 'float', 'Char': 'string', } argp = ArgumentParser() argp.add_argument( '--input', '-i', metavar='<backup_file.tachibk | backup_file.proto.gz | decoded_backup.json>', help='File extension defines whether to decode a backup file to JSON or encode it back', type=Path, ) argp.add_argument( '--output', '-o', default='output.json', metavar='<output.json | encoded_backup.tachibk>', help='When encoding, TACHIBK or PROTO.GZ will additionally recompress the backup file', type=Path, ) argp.add_argument( '--fork', default=list(FORKS.keys())[0], choices=FORKS.keys(), metavar=f'<{" | ".join(FORKS.keys())}>', help='Fork for the backup schema. Default: mihon', ) argp.add_argument( '--dump-schemas', action='store_true', help='Dump protobuf schemas from all supported forks', ) argp.add_argument( '--convert-preferences', action='store_true', help='Convert the preference values into human-readable format.\n[EXPERIMENTAL!] May not be encoded back into a backup file', ) args = argp.parse_args() def fetch_schema(fork: str) -> list[tuple[str, str]]: files: list[tuple[str, str]] = [] git = get( f'https://api.github.com/repos/{fork}/contents/app/src/main/java/eu/kanade/tachiyomi/data/backup/models' ).json() for entry in git: if entry.get('type') == 'file': files.append((entry.get('name'), entry.get('download_url'))) elif entry.get('type') == 'dir': for sub_entry in get(entry.get('url')).json(): if sub_entry.get('type') == 'file': files.append((sub_entry.get('name'), sub_entry.get('download_url'))) return files def parse_model(model: str) -> list[str]: data = get(model).text message: list[str] = [] for name in re.finditer(CLASS_RE, data, re.MULTILINE): message.append('message {name} {{'.format(name=name.group('name'))) for field in re.finditer(PROTONUMBER_RE, name.group('defs'), re.MULTILINE): message.append( ' {repeated} {type} {name} = {number};'.format( repeated='repeated' if field.group('list') else 'optional' if field.group('optional') else 'required', type=DATA_TYPES.get( field.group('type'), DATA_TYPES.get( field.group('list'), field.group('list') or field.group('type'), ), ), name=field.group('name'), number=field.group('number') or 1 if not name.group('name').startswith('Broken') else int(field.group('number')) + 1, ) ) message.append('}\n') return message def proto_gen(file: str = None, fork: str = args.fork): # Hard-coded exceptions to make parsing easier schema = '''syntax = "proto2"; enum UpdateStrategy { ALWAYS_UPDATE = 0; ONLY_FETCH_ONCE = 1; } message PreferenceValue { required string type = 1; required bytes truevalue = 2; } '''.splitlines() print(f'... Fetching from {fork.upper()}') for i in fetch_schema(FORKS[fork]): print(f'... Parsing {i[0]}') schema.append(f'// {i[0]}') schema.extend(parse_model(i[1])) filename = file or f'schema-{fork}.proto' print(f'Writing {filename}') print('\n'.join(schema), file=open(filename, 'wt')) if args.dump_schemas: print('Generating Protobuf schemas') for fork in FORKS: proto_gen(fork=fork) print('END') exit(0) try: from schema_pb2 import Backup except (ModuleNotFoundError, NameError): print('No protobuf schema found...') proto_gen('schema.proto') print('Generating Python sources...') try: run(['protoc', '--python_out=.', '--pyi_out=.', 'schema.proto']) except FileNotFoundError: print( 'ERROR! Protoc not found.', 'Download at https://github.com/protocolbuffers/protobuf/releases/latest', ) exit(1) try: from schema_pb2 import Backup except (ModuleNotFoundError, NameError): print('ERROR! Still unable to find the protobuf schema. Aborting.') exit(1) def read_backup(input: str) -> str | bytes: if input.endswith('.tachibk') or input.endswith('.proto.gz'): with gzip.open(input, 'rb') as zip: backup_data = zip.read() with open('extracted_tachibk', 'wb') as file: file.write(backup_data) else: try: with open('extracted_tachibk', 'rb') as file: backup_data = file.read() except OSError: print('ERROR! No Backup to process.') argp.print_help() exit(1) return backup_data def parse_backup(backup_data) -> Backup: message = Backup() message.ParseFromString(backup_data) return message def write_json(message: Backup) -> None: message_dict = MessageToDict(message) if args.convert_preferences: print('Translating Preferences...') for idx, pref in enumerate(message_dict.get('backupPreferences')): message_dict['backupPreferences'][idx]['value']['truevalue'] = readable_preference(pref) for source_index, source in enumerate(message_dict.get('backupSourcePreferences')): for idx, pref in enumerate(source.get('prefs')): message_dict['backupSourcePreferences'][source_index]['prefs'][idx]['value'][ 'truevalue' ] = readable_preference(pref) with open(args.output, 'wt') as file: file.write(dumps(message_dict, indent=2)) print(f'Backup decoded to "{args.output}"') def readable_preference(preference_value: dict): true_value = preference_value['value']['truevalue'] match preference_value['value']['type'].split('.')[-1].removesuffix('PreferenceValue'): case 'Boolean': return bool(varint.decode_bytes(b64decode(true_value)[1:])) case 'Int' | 'Long': return varint.decode_bytes(b64decode(true_value)[1:]) case 'Float': return unpack( 'f', b64decode(true_value)[1:], )[0] case 'String': return b64decode(true_value)[2:].decode('utf-8') case 'StringSet': bar = list(b64decode(true_value)) new_list = [] for byte in bar: if byte == bar[0]: new_list.append([]) continue new_list[-1].append(byte) for index, entry in enumerate(new_list): new_list[index] = bytes(entry[1:]).decode('utf-8') return new_list case _: return None def bytes_preference(preference_value: dict): true_value = preference_value['value']['truevalue'] print(f'Parsing {true_value}') match preference_value['value']['type'].split('.')[-1].removesuffix('PreferenceValue'): case 'Boolean': return b64encode(b'\x08' + int(true_value).to_bytes()).decode() case 'Int' | 'Long': return b64encode(b'\x08' + varint.encode(true_value)).decode() case 'Float': return b64encode(b'\r' + pack('f', true_value)).decode() case 'String': return b64encode(b'\n' + len(true_value).to_bytes() + true_value.encode()).decode() case 'StringSet': new_bytes = b'' for val in true_value: new_bytes += b'\n' + len(val).to_bytes() + val.encode() return b64encode(new_bytes).decode() case _: return '' def parse_json(input: str) -> bytes: try: with open(input, 'r') as file: message_dict = loads(file.read()) except OSError: print('ERROR! Could not read the JSON file.') exit(1) # Check if --convert-preferences was used for idx, pref in enumerate(message_dict.get('backupPreferences', [])): if 'String' not in pref['value']['type'] and isinstance(pref['value']['truevalue'], str): break message_dict['backupPreferences'][idx]['value']['truevalue'] = bytes_preference(pref) for source_index, source in enumerate(message_dict.get('backupSourcePreferences', [])): for idx, pref in enumerate(source.get('prefs')): if 'String' not in pref['value']['type'] and isinstance( pref['value']['truevalue'], str ): break message_dict['backupSourcePreferences'][source_index]['prefs'][idx]['value'][ 'truevalue' ] = bytes_preference(pref) try: return Parse(dumps(message_dict), Backup()).SerializeToString() except ParseError as e: print('The input JSON file is invalid.', e) exit(1) def write_backup(message: bytes) -> None: compression = True output = 'encoded_backup.tachibk' if str(args.output) == 'output.json' else str(args.output) if output.endswith('.proto.gz') or output.endswith('.tachibk'): with gzip.open(output, 'wb') as zip: zip.write(message) else: with open(output, 'wb') as file: file.write(message) compression = False print(f'{"C" if compression else "Unc"}ompressed backup written to {output}') if __name__ == '__main__': input = str(args.input) if input.endswith('.json'): write_backup(parse_json(input)) else: write_json(parse_backup(read_backup(input)))
10,619
Python
.py
273
30.604396
193
0.588595
BrutuZ/tachibk-converter
8
2
0
GPL-2.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,792
RunAs.py
rkbennett_RunAsPy/RunAs.py
import argparse import RunAsPy parser = argparse.ArgumentParser(description="") parser.add_argument('-d', '--domain', help="", nargs="?", dest="domainName") parser.add_argument('-u', '--username', help="", nargs="?", required=True) parser.add_argument('-P', '--password', help="", nargs="?", required=True) parser.add_argument('-c', '--command', help="", nargs="*", dest="cmd", required=True) parser.add_argument('-t', '--timeout', help="", nargs="?", default=120000, dest="processTimeout", type=int) parser.add_argument('-l', '--logon-type', help="", nargs="?", default=2, dest="logonType", type=int, choices=[2, 3, 4, 5, 7, 8, 9]) parser.add_argument('-f', '--function', help="", nargs="?", dest="createProcessFunction", default=RunAsPy.DefaultCreateProcessFunction(), type=int) parser.add_argument('-r', '--remote', help="", nargs="?", default=None) parser.add_argument('-p', '--force-profile', help="", action="store_true", default=False, dest="forceUserProfileCreation") parser.add_argument('-b', '--bypass-uac', help="", action="store_true", default=False, dest="bypassUac") parser.add_argument('-i', '--remote-impersonation', help="", action="store_true", default=False, dest="remoteImpersonation") parser.add_argument('-v', '--verbose', help="increase verbosity", action="store_true") args = parser.parse_args() if args.remote: args.processTimeout = 0 print(RunAsPy.Runas(**args.__dict__))
1,405
Python
.py
19
72.578947
147
0.686913
rkbennett/RunAsPy
8
1
0
AGPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,793
windefs.py
rkbennett_RunAsPy/RunAsPy/windefs.py
import ctypes import ctypes.wintypes UOI_NAME = 2 ERROR_LOGON_TYPE_NOT_GRANTED = 1385 LOGON32_LOGON_INTERACTIVE = ctypes.wintypes.DWORD(2) LOGON32_LOGON_NETWORK = ctypes.wintypes.DWORD(3) LOGON32_LOGON_BATCH = ctypes.wintypes.DWORD(4) LOGON32_LOGON_SERVICE = ctypes.wintypes.DWORD(5) LOGON32_LOGON_NETWORK_CLEARTEXT = ctypes.wintypes.DWORD(8) LOGON32_LOGON_NEW_CREDENTIALS = ctypes.wintypes.DWORD(9) LOGON_WITH_PROFILE = ctypes.c_uint32(1) DUPLICATE_SAME_ACCESS = ctypes.c_uint(0x2) LOGON32_PROVIDER_DEFAULT = ctypes.wintypes.DWORD(0) LOGON32_PROVIDER_WINNT50 = ctypes.wintypes.DWORD(3) Startf_UseStdHandles = 0x00000100 BUFFER_SIZE_PIPE = 1048576 READ_CONTROL = 0x00020000 WRITE_DAC = 0x00040000 DESKTOP_WRITEOBJECTS = 0x00000080 DESKTOP_READOBJECTS = 0x00000001 ERROR_INSUFFICIENT_BUFFER = 122 ERROR_INVALID_FLAGS = 1004 ERROR_NO_TOKEN = 1008 SECURITY_DESCRIPTOR_REVISION = 1 ACL_REVISION = 2 MAXDWORD = 0xffffffff MAX_PATH = 260 ACCESS_ALLOWED_ACE_TYPE = 0x0 CONTAINER_INHERIT_ACE = 0x2 INHERIT_ONLY_ACE = 0x8 OBJECT_INHERIT_ACE = 0x1 NO_PROPAGATE_INHERIT_ACE = 0x4 LOGON_NETCREDENTIALS_ONLY = 2 CREATE_NO_WINDOW = 0x08000000 CREATE_SUSPENDED = 0x00000004 ERROR_MORE_DATA = 234 CREATE_UNICODE_ENVIRONMENT = 0x00000400 PSID = ctypes.c_void_p privileges = [ "SeAssignPrimaryTokenPrivilege", "SeAuditPrivilege", "SeBackupPrivilege", "SeChangeNotifyPrivilege", "SeCreateGlobalPrivilege", "SeCreatePagefilePrivilege", "SeCreatePermanentPrivilege", "SeCreateSymbolicLinkPrivilege", "SeCreateTokenPrivilege", "SeDebugPrivilege", "SeDelegateSessionUserImpersonatePrivilege", "SeEnableDelegationPrivilege", "SeImpersonatePrivilege", "SeIncreaseBasePriorityPrivilege", "SeIncreaseQuotaPrivilege", "SeIncreaseWorkingSetPrivilege", "SeLoadDriverPrivilege", "SeLockMemoryPrivilege", "SeMachineAccountPrivilege", "SeManageVolumePrivilege", "SeProfileSingleProcessPrivilege", "SeRelabelPrivilege", "SeRemoteShutdownPrivilege", "SeRestorePrivilege", "SeSecurityPrivilege", "SeShutdownPrivilege", "SeSyncAgentPrivilege", "SeSystemEnvironmentPrivilege", "SeSystemProfilePrivilege", "SeSystemtimePrivilege", "SeTakeOwnershipPrivilege", "SeTcbPrivilege", "SeTimeZonePrivilege", "SeTrustedCredManAccessPrivilege", "SeUndockPrivilege", "SeUnsolicitedInputPrivilege" ] kernel32 = ctypes.WinDLL("kernel32.dll") user32 = ctypes.WinDLL("User32.dll") ws2_32 = ctypes.WinDLL("ws2_32.dll") advapi32 = ctypes.WinDLL("Advapi32.dll") userenv = ctypes.WinDLL("Userenv.dll") connect = ws2_32.connect closesocket = ws2_32.closesocket WSASocket = ws2_32.WSASocketA WSAStartup = ws2_32.WSAStartup ReadFile = kernel32.ReadFile CloseHandle = kernel32.CloseHandle CreatePipe = kernel32.CreatePipe CreateProcessW = kernel32.CreateProcessW DuplicateHandle = kernel32.DuplicateHandle SetNamedPipeHandleState = kernel32.SetNamedPipeHandleState WaitForSingleObject = kernel32.WaitForSingleObject GetCurrentProcessId = kernel32.GetCurrentProcessId ProcessIdToSessionId = kernel32.ProcessIdToSessionId GetTokenInformation = advapi32.GetTokenInformation GetCurrentThread = kernel32.GetCurrentThread GetCurrentProcess = kernel32.GetCurrentProcess ResumeThread = kernel32.ResumeThread OpenProcess = kernel32.OpenProcess LogonUser = advapi32.LogonUserA GetSecurityDescriptorDacl = advapi32.GetSecurityDescriptorDacl LookupAccountName = advapi32.LookupAccountNameA GetAclInformation = advapi32.GetAclInformation InitializeSecurityDescriptor = advapi32.InitializeSecurityDescriptor GetLengthSid = advapi32.GetLengthSid InitializeAcl = advapi32.InitializeAcl GetAce = advapi32.GetAce AddAce = advapi32.AddAce CopySid = advapi32.CopySid ConvertSidToStringSid = advapi32.ConvertSidToStringSidA SetThreadToken = advapi32.SetThreadToken RevertToSelf = advapi32.RevertToSelf AdjustTokenPrivileges = advapi32.AdjustTokenPrivileges LookupPrivilegeName = advapi32.LookupPrivilegeNameA SetSecurityInfo = advapi32.SetSecurityInfo CreateProcessWithLogonW = advapi32.CreateProcessWithLogonW ImpersonateLoggedOnUser = advapi32.ImpersonateLoggedOnUser AllocateAndInitializeSid = advapi32.AllocateAndInitializeSid OpenProcessToken = advapi32.OpenProcessToken GetSidSubAuthorityCount = advapi32.GetSidSubAuthorityCount GetSidSubAuthority = advapi32.GetSidSubAuthority OpenThreadToken = advapi32.OpenThreadToken DuplicateToken = advapi32.DuplicateToken DuplicateTokenEx = advapi32.DuplicateTokenEx AddAccessAllowedAce = advapi32.AddAccessAllowedAce SetSecurityDescriptorDacl = advapi32.SetSecurityDescriptorDacl SetTokenInformation = advapi32.SetTokenInformation LookupPrivilegeValue = advapi32.LookupPrivilegeValueA CreateProcessWithTokenW =advapi32.CreateProcessWithTokenW CreateProcessAsUser = advapi32.CreateProcessAsUserA GetProcessWindowStation = user32.GetProcessWindowStation GetUserObjectInformation = user32.GetUserObjectInformationA OpenWindowStation = user32.OpenWindowStationA SetProcessWindowStation = user32.SetProcessWindowStation OpenDesktop = user32.OpenDesktopA GetUserObjectSecurity = user32.GetUserObjectSecurity SetUserObjectSecurity = user32.SetUserObjectSecurity GetUserProfileDirectory = userenv.GetUserProfileDirectoryA LoadUserProfile = userenv.LoadUserProfileA CreateEnvironmentBlock = userenv.CreateEnvironmentBlock UnloadUserProfile = userenv.UnloadUserProfile DestroyEnvironmentBlock = userenv.DestroyEnvironmentBlock OpenThreadToken.restype = ctypes.c_bool class LUID(ctypes.Structure): _fields_ = [ ('LowPart', ctypes.wintypes.DWORD), ('HighPart', ctypes.c_long) ] class LUID_AND_ATTRIBUTES(ctypes.Structure): _fields_ = [ ('Luid', LUID), ('Attributes', ctypes.wintypes.DWORD) ] class SID_AND_ATTRIBUTES(ctypes.Structure): _fields_ = [ ('Sid', PSID), ('Attributes', ctypes.wintypes.DWORD) ] class TOKEN_MANDATORY_LABEL(ctypes.Structure): _fields_ = [ ('Label', SID_AND_ATTRIBUTES), ] class TOKEN_PRIVILEGES(ctypes.Structure): _fields_ = [ ('PrivilegeCount', ctypes.wintypes.DWORD), ('Privileges', (LUID_AND_ATTRIBUTES * 64)) ] class STARTUPINFO(ctypes.Structure): _fields_ = [ ('cb', ctypes.wintypes.DWORD), ('lpReserved', ctypes.wintypes.LPWSTR), ('lpDesktop', ctypes.wintypes.LPWSTR), ('lpTitle', ctypes.wintypes.LPWSTR), ('dwX', ctypes.wintypes.DWORD), ('dwY', ctypes.wintypes.DWORD), ('dwXSize', ctypes.wintypes.DWORD), ('dwYSize', ctypes.wintypes.DWORD), ('dwXCountChars', ctypes.wintypes.DWORD), ('dwYCountChars', ctypes.wintypes.DWORD), ('dwFillAttribute', ctypes.wintypes.DWORD), ('dwFlags', ctypes.wintypes.DWORD), ('wShowWindow', ctypes.wintypes.WORD), ('cbReserved2', ctypes.wintypes.WORD), ('lpReserved2', ctypes.wintypes.LPBYTE), ('hStdInput', ctypes.wintypes.HANDLE), ('hStdOutput', ctypes.wintypes.HANDLE), ('hStdError', ctypes.wintypes.HANDLE) ] LPSTARTUPINFOW = ctypes.POINTER(STARTUPINFO) class PROCESS_INFORMATION(ctypes.Structure): _fields_ = [ ("process", ctypes.wintypes.HANDLE), ("thread", ctypes.wintypes.HANDLE), ("processId", ctypes.wintypes.DWORD), ("threadId", ctypes.wintypes.DWORD) ] LPPROCESS_INFORMATION = ctypes.POINTER(PROCESS_INFORMATION) class ACL_SIZE_INFORMATION(ctypes.Structure): _fields_ = [ ('AceCount', ctypes.wintypes.DWORD), ('AclBytesInUse', ctypes.wintypes.DWORD), ('AcleBytesFree', ctypes.wintypes.DWORD) ] class SID_IDENTIFIER_AUTHORITY(ctypes.Structure): _fields_ = [ ('Value', (ctypes.c_byte * 6)), ] class PROFILEINFO(ctypes.Structure): _fields_ = [ ('dwSize', ctypes.wintypes.DWORD), ('dwFlags', ctypes.wintypes.DWORD), ('lpUserName', ctypes.wintypes.LPSTR), ('lpProfilePath', ctypes.wintypes.LPSTR), ('lpDefaultPath', ctypes.wintypes.LPSTR), ('lpServerName', ctypes.wintypes.LPSTR), ('lpPolicyPath', ctypes.wintypes.LPSTR), ('hProfile', ctypes.c_void_p) ] class SECURITY_IMPERSONATION_LEVEL(object): SecurityAnonymous = ctypes.c_int(0) SecurityIdentification = ctypes.c_int(1) SecurityImpersonation = ctypes.c_int(2) SecurityDelegation = ctypes.c_int(3) class AddressFamily(object): XAppleTalk = ctypes.c_int(16) Atm = ctypes.c_int(22) Banyan = ctypes.c_int(21) Ccitt = ctypes.c_int(10) Chaos = ctypes.c_int(5) Cluster = ctypes.c_int(24) ControllerAreaNetwork = ctypes.c_int(65537) DataKit = ctypes.c_int(9) DataLink = ctypes.c_int(13) DecNet = ctypes.c_int(12) Ecma = ctypes.c_int(8) FireFox = ctypes.c_int(19) HyperChannel = ctypes.c_int(15) Ieee12844 = ctypes.c_int(25) ImpLink = ctypes.c_int(3) InterNetwork = ctypes.c_int(2) InterNetworkV6 = ctypes.c_int(23) Ipx = ctypes.c_int(6) Irda = ctypes.c_int(26) Iso = ctypes.c_int(7) Lat = ctypes.c_int(1) Max = ctypes.c_int(2) NetBios = ctypes.c_int(17) NetworkDesigners = ctypes.c_int(28) NS = ctypes.c_int(6) Osi = ctypes.c_int(7) Packet = ctypes.c_int(65536) Pup = ctypes.c_int(4) Sna = ctypes.c_int(11) Unix = ctypes.c_int(1) Unknown = ctypes.c_int(-1) Unspecified = ctypes.c_int() VoiceView = ctypes.c_int(1) class ProtocolType(object): Ggp = ctypes.c_int(3) Icmp = ctypes.c_int(1) IcmpV6 = ctypes.c_int(58) Idp = ctypes.c_int(22) Igmp = ctypes.c_int(2) IP = ctypes.c_int(0) IPSecAuthenticationHeader = ctypes.c_int(51) IPSecEncapsulatingSecurityPayload = ctypes.c_int(50) IPv4 = ctypes.c_int(4) IPv6 = ctypes.c_int(41) IPv6DestinationOptions = ctypes.c_int(60) IPv6FragmentHeader = ctypes.c_int(44) IPv6HopByHopOptions = ctypes.c_int(0) IPv6NoNextHeader = ctypes.c_int(59) IPv6RoutingHeader = ctypes.c_int(43) Ipx = ctypes.c_int(1000) ND = ctypes.c_int(77) Pup = ctypes.c_int(12) Raw = ctypes.c_int(255) Spx = ctypes.c_int(1256) SpxII = ctypes.c_int(1257) Tcp = ctypes.c_int(6) Udp = ctypes.c_int(17) Unknown = ctypes.c_int(-1) Unspecified = ctypes.c_int(0) class SocketType(object): Dgram = ctypes.c_int(2) Raw = ctypes.c_int(3) Rdm = ctypes.c_int(4) Seqpacket = ctypes.c_int(5) Stream = ctypes.c_int(1) Unknown = ctypes.c_int(-1) class SE_OBJECT_TYPE(object): SE_UNKNOWN_OBJECT_TYPE = ctypes.c_int(0) SE_FILE_OBJECT = ctypes.c_int(1) SE_SERVICE = ctypes.c_int(2) SE_PRINTER = ctypes.c_int(3) SE_REGISTRY_KEY = ctypes.c_int(4) SE_LMSHARE = ctypes.c_int(5) SE_KERNEL_OBJECT = ctypes.c_int(6) SE_WINDOW_OBJECT = ctypes.c_int(7) SE_DS_OBJECT = ctypes.c_int(8) SE_DS_OBJECT_ALL = ctypes.c_int(9) SE_PROVIDER_DEFINED_OBJECT = ctypes.c_int(10) SE_WMIGUID_OBJECT = ctypes.c_int(11) SE_REGISTRY_WOW64_32KEY = ctypes.c_int(12) class SECURITY_INFORMATION(object): OWNER_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x00000001) GROUP_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x00000002) DACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x00000004) SACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x00000008) UNPROTECTED_SACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x10000000) UNPROTECTED_DACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x20000000) PROTECTED_SACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x40000000) PROTECTED_DACL_SECURITY_INFORMATION = ctypes.wintypes.DWORD(0x80000000) class SID_NAME_USE(object): SidTypeUser = ctypes.c_int(1) SidTypeGroup = ctypes.c_int(2) SidTypeDomain = ctypes.c_int(3) SidTypeAlias = ctypes.c_int(4) SidTypeWellKnownGroup = ctypes.c_int(5) SidTypeDeletedAccount = ctypes.c_int(6) SidTypeInvalid = ctypes.c_int(7) SidTypeUnknown = ctypes.c_int(8) SidTypeComputer = ctypes.c_int(9) SidTypeLabel = ctypes.c_int(10) class TOKEN_ELEVATION(ctypes.Structure): _fields_ = [ ('TokenIsElevated', ctypes.c_uint32) ] class TOKEN_ELEVATION_TYPE(ctypes.Structure): _fields_ = [ ('TokenElevationType', ctypes.c_uint32) ] class ACL_INFORMATION_CLASS(object): AclRevisionInformation = ctypes.wintypes.DWORD(1) AclSizeInformation = ctypes.wintypes.DWORD(2) class TokenGroupAttributes(object): Disabled = ctypes.wintypes.DWORD(0) SE_GROUP_MANDATORY = ctypes.wintypes.DWORD(1) SE_GROUP_ENABLED_BY_DEFAULT = ctypes.wintypes.DWORD(0x2) SE_GROUP_ENABLED = ctypes.wintypes.DWORD(0x4) SE_GROUP_OWNER = ctypes.wintypes.DWORD(0x8) SE_GROUP_USE_FOR_DENY_ONLY = ctypes.wintypes.DWORD(0x10) SE_GROUP_INTEGRITY = ctypes.wintypes.DWORD(0x20) SE_GROUP_INTEGRITY_ENABLED = ctypes.wintypes.DWORD(0x40) SE_GROUP_RESOURCE = ctypes.wintypes.DWORD(0x20000000) SE_GROUP_LOGON_ID = ctypes.wintypes.DWORD(0xC0000000) class TOKEN_INFORMATION_CLASS(object): TokenUser = ctypes.c_int(1) TokenGroups = ctypes.c_int(2) TokenPrivileges = ctypes.c_int(3) TokenOwner = ctypes.c_int(4) TokenPrimaryGroup = ctypes.c_int(5) TokenDefaultDacl = ctypes.c_int(6) TokenSource = ctypes.c_int(7) TokenType = ctypes.c_int(8) TokenImpersonationLevel = ctypes.c_int(9) TokenStatistics = ctypes.c_int(10) TokenRestrictedSids = ctypes.c_int(11) TokenSessionId = ctypes.c_int(12) TokenGroupsAndPrivileges = ctypes.c_int(13) TokenSessionReference = ctypes.c_int(14) TokenSandBoxInert = ctypes.c_int(15) TokenAuditPolicy = ctypes.c_int(16) TokenOrigin = ctypes.c_int(17) TokenElevationType = ctypes.c_int(18) TokenLinkedToken = ctypes.c_int(19) TokenElevation = ctypes.c_int(20) TokenHasRestrictions = ctypes.c_int(21) TokenAccessInformation = ctypes.c_int(22) TokenVirtualizationAllowed = ctypes.c_int(23) TokenVirtualizationEnabled = ctypes.c_int(24) TokenIntegrityLevel = ctypes.c_int(25) TokenUIAccess = ctypes.c_int(26) TokenMandatoryPolicy = ctypes.c_int(27) TokenLogonSid = ctypes.c_int(28) TokenIsAppContainer = ctypes.c_int(29) TokenCapabilities = ctypes.c_int(30) TokenAppContainerSid = ctypes.c_int(31) TokenAppContainerNumber = ctypes.c_int(32) TokenUserClaimAttributes = ctypes.c_int(33) TokenDeviceClaimAttributes = ctypes.c_int(34) TokenRestrictedUserClaimAttributes = ctypes.c_int(35) TokenRestrictedDeviceClaimAttributes = ctypes.c_int(36) TokenDeviceGroups = ctypes.c_int(37) TokenRestrictedDeviceGroups = ctypes.c_int(38) TokenSecurityAttributes = ctypes.c_int(39) TokenIsRestricted = ctypes.c_int(40) TokenProcessTrustLevel = ctypes.c_int(41) TokenPrivateNameSpace = ctypes.c_int(42) TokenSingletonAttributes = ctypes.c_int(43) TokenBnoIsolation = ctypes.c_int(44) TokenChildProcessFlags = ctypes.c_int(45) TokenIsLessPrivilegedAppContainer = ctypes.c_int(46) TokenIsSandboxed = ctypes.c_int(47) TokenIsAppSilo = ctypes.c_int(48) TokenLoggingInformation = ctypes.c_int(49) MaxTokenInfoClass = ctypes.c_int(50) class SECURITY_ATTRIBUTES(ctypes.Structure): _fields_ = [ ('nLength', ctypes.wintypes.DWORD), ('lpSecurityDescriptor', ctypes.wintypes.LPVOID), ('bInheritHandle', ctypes.c_bool) ] class WSADATA(ctypes.Structure): _fields_ = [ ('wVersion', ctypes.c_short), ('wHighVersion', ctypes.c_short), ('iMaxSockets', ctypes.c_short), ('iMaxUdpDg', ctypes.c_short), ('lpVendorInfo', ctypes.c_void_p), ('szDescription', ctypes.POINTER(ctypes.c_char * 257)), ('szSystemStatus', ctypes.POINTER(ctypes.c_char * 129)) ] class ACL(ctypes.Structure): _fields_ = [ ('AclRevision', ctypes.c_byte), ('Sbz1', ctypes.c_byte), ('AclSize', ctypes.wintypes.WORD), ('AceCount', ctypes.wintypes.WORD), ('Sbz2', ctypes.wintypes.WORD) ] class SECURITY_DESCRIPTOR(ctypes.Structure): _fields_ = [ ('Revision', ctypes.c_byte), ('Sbz1', ctypes.c_byte), ('Control', ctypes.wintypes.WORD), ('Owner', ctypes.c_void_p), ('Group', ctypes.c_void_p), ('Sacl', ctypes.POINTER(ACL)), ('Dacl', ctypes.POINTER(ACL)) ] class ACCESS_MASK(object): DELETE = 0x00010000 READ_CONTROL = 0x00020000 WRITE_DAC = 0x00040000 WRITE_OWNER = 0x00080000 SYNCHRONIZE = 0x00100000 STANDARD_RIGHTS_REQUIRED = 0x000F0000 STANDARD_RIGHTS_READ = READ_CONTROL STANDARD_RIGHTS_WRITE = READ_CONTROL STANDARD_RIGHTS_EXECUTE = READ_CONTROL STANDARD_RIGHTS_ALL = 0x001F0000 SPECIFIC_RIGHTS_ALL = 0x0000FFFF GENERIC_READ = 0x80000000 GENERIC_WRITE = 0x40000000 GENERIC_EXECUTE = 0x20000000 GENERIC_ALL = 0x10000000 GENERIC_ACCESS = (GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL) WINSTA_ENUMDESKTOPS = 0x00000001 WINSTA_READATTRIBUTES = 0x00000002 WINSTA_ACCESSCLIPBOARD = 0x00000004 WINSTA_CREATEDESKTOP = 0x00000008 WINSTA_WRITEATTRIBUTES = 0x00000010 WINSTA_ACCESSGLOBALATOMS = 0x00000020 WINSTA_EXITWINDOWS = 0x00000040 WINSTA_ENUMERATE = 0x00000100 WINSTA_READSCREEN = 0x00000200 WINSTA_ALL = ( WINSTA_ACCESSCLIPBOARD | WINSTA_ACCESSGLOBALATOMS | WINSTA_CREATEDESKTOP | WINSTA_ENUMDESKTOPS | WINSTA_ENUMERATE | WINSTA_EXITWINDOWS | WINSTA_READATTRIBUTES | WINSTA_READSCREEN | WINSTA_WRITEATTRIBUTES | DELETE | READ_CONTROL | WRITE_DAC | WRITE_OWNER ) DESKTOP_READOBJECTS = 0x00000001 DESKTOP_CREATEWINDOW = 0x00000002 DESKTOP_CREATEMENU = 0x00000004 DESKTOP_HOOKCONTROL = 0x00000008 DESKTOP_JOURNALRECORD = 0x00000010 DESKTOP_JOURNALPLAYBACK = 0x00000020 DESKTOP_ENUMERATE = 0x00000040 DESKTOP_WRITEOBJECTS = 0x00000080 DESKTOP_SWITCHDESKTOP = 0x00000100 DESKTOP_ALL = ( DESKTOP_READOBJECTS | DESKTOP_CREATEWINDOW | DESKTOP_CREATEMENU | DESKTOP_HOOKCONTROL | DESKTOP_JOURNALRECORD | DESKTOP_JOURNALPLAYBACK | DESKTOP_ENUMERATE | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP | STANDARD_RIGHTS_REQUIRED ) class ACE_HEADER(ctypes.Structure): _fields_ = [ ('AceType', ctypes.c_byte), ('AceFlags', ctypes.c_byte), ('AceSize', ctypes.c_ushort), ] class TOKEN_PRIVILEGES_2(ctypes.Structure): _fields_ = [ ('PrivilegeCount', ctypes.c_uint32), ('Luid', LUID), ('Attributes', ctypes.wintypes.DWORD) ] class ACCESS_ALLOWED_ACE(ctypes.Structure): _fields_ = [ ('Header', ACE_HEADER), ('Mask', ctypes.wintypes.DWORD), ('SidStart', ctypes.wintypes.DWORD) ] class SOCKADDR_IN(ctypes.Structure): _fields_ = [ ('sin_family', ctypes.c_short), ('sin_port', ctypes.c_short), ('sin_addr', ctypes.c_ulong), ('sin_zero', (ctypes.c_char * 8)) ] class IntegrityLevel(object): Same = -2 Unknown = -1 Untrusted = 0 Low = 0x1000 Medium = 0x2000 High = 0x3000 System = 0x4000 ProtectedProcess = 0x5000 CreateProcessWithLogonW.argtypes = [ ctypes.wintypes.LPCWSTR, ctypes.wintypes.LPCWSTR, ctypes.wintypes.LPCWSTR, ctypes.wintypes.DWORD, ctypes.wintypes.LPCWSTR, ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD, ctypes.wintypes.LPCWSTR, ctypes.wintypes.LPCWSTR, LPSTARTUPINFOW, LPPROCESS_INFORMATION ] CreateProcessWithTokenW.argtypes = [ ctypes.wintypes.HANDLE, ctypes.wintypes.DWORD, ctypes.wintypes.LPCWSTR, ctypes.wintypes.LPWSTR, ctypes.wintypes.DWORD, ctypes.wintypes.LPVOID, ctypes.wintypes.LPCWSTR, LPSTARTUPINFOW, LPPROCESS_INFORMATION ] LogonUser.argtypes = [ ctypes.wintypes.LPCSTR, ctypes.wintypes.LPCSTR, ctypes.wintypes.LPCSTR, ctypes.wintypes.DWORD, ctypes.wintypes.DWORD, ctypes.POINTER(ctypes.wintypes.HANDLE) ] GetUserProfileDirectory.argtypes = [ ctypes.wintypes.HANDLE, ctypes.wintypes.LPSTR, ctypes.wintypes.LPDWORD ] CreateProcessW.argtypes = [ ctypes.wintypes.LPCWSTR, ctypes.wintypes.LPWSTR, ctypes.c_void_p, ctypes.c_void_p, ctypes.c_bool, ctypes.wintypes.DWORD, ctypes.wintypes.LPVOID, ctypes.wintypes.LPCWSTR, ctypes.POINTER(STARTUPINFO), ctypes.POINTER(PROCESS_INFORMATION) ] GetSidSubAuthorityCount.restype = ctypes.POINTER(ctypes.c_byte) GetSidSubAuthority.restype = ctypes.POINTER(ctypes.wintypes.DWORD) LookupAccountName.argtypes = [ ctypes.wintypes.LPCSTR, ctypes.wintypes.LPCSTR, PSID, ctypes.POINTER(ctypes.c_ulong), ctypes.wintypes.LPSTR, ctypes.POINTER(ctypes.c_ulong), ctypes.POINTER(ctypes.c_int) ] LookupAccountName.restype = ctypes.wintypes.BOOL
21,309
Python
.py
545
34.440367
152
0.716812
rkbennett/RunAsPy
8
1
0
AGPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,794
__init__.py
rkbennett_RunAsPy/RunAsPy/__init__.py
import os import ctypes import ctypes.wintypes import socket import struct import logging from .windefs import * def convertAttributeToString(attribute): if attribute == 0: return "Disabled" if attribute == 1: return "Enabled Default" if attribute == 2: return "Enabled" if attribute == 3: return "Enabled|Enable Default" return "Error" class runas_logging_formatter(logging.Formatter): grey = "\x1b[38;20m" cyan = "\x1b[36;20m" yellow = "\x1b[33;20m" red = "\x1b[31;20m" bold_red = "\x1b[31;1m" reset = "\x1b[0m" log_format = "%(levelname)s: %(message)s" logger_formats = { logging.DEBUG: grey + "[*] " + log_format + reset, logging.INFO: cyan + "[+] " + log_format + reset, logging.WARNING: yellow + "[!] " + log_format + reset, logging.ERROR: red + "[-] " + log_format + reset, logging.CRITICAL: bold_red + log_format + reset } def format(self, record): log_fmt = self.logger_formats.get(record.levelno) formatter = logging.Formatter(log_fmt) return formatter.format(record) class RunAsPyException(Exception): def __init__(self, value, showError=True): if showError: error = ctypes.GetLastError() err_str = ctypes.WinError(error).strerror self.value = f"{ value } failed with error { error }: { err_str }" else: self.value = value def __str__(self): return(repr(self.value)) class AccessToken(object): SECURITY_MANDATORY_UNTRUSTED_RID = 0 SECURITY_MANDATORY_LOW_RID = 0x1000 SECURITY_MANDATORY_MEDIUM_RID = 0x2000 SECURITY_MANDATORY_HIGH_RID = 0x3000 SECURITY_MANDATORY_SYSTEM_RID = 0x4000 SECURITY_MANDATORY_PROTECTED_PROCESS_RID = 0x5000 SE_PRIVILEGE_ENABLED = 0x00000002 MANDATORY_LABEL_AUTHORITY = bytes([0,0,0,0,0,16]) STANDARD_RIGHTS_REQUIRED = 0x000F0000 STANDARD_RIGHTS_READ = 0x00020000 TOKEN_ASSIGN_PRIMARY = 0x0001 TOKEN_DUPLICATE = 0x0002 TOKEN_IMPERSONATE = 0x0004 TOKEN_QUERY = 0x0008 TOKEN_QUERY_SOURCE = 0x0010 TOKEN_ADJUST_PRIVILEGES = 0x0020 TOKEN_ADJUST_GROUPS = 0x0040 TOKEN_ADJUST_DEFAULT = 0x0080 TOKEN_ADJUST_SESSIONID = 0x0100 TOKEN_READ = (STANDARD_RIGHTS_READ | TOKEN_QUERY) TOKEN_ALL_ACCESS = ( STANDARD_RIGHTS_REQUIRED | TOKEN_ASSIGN_PRIMARY | TOKEN_DUPLICATE | TOKEN_IMPERSONATE | TOKEN_QUERY | TOKEN_QUERY_SOURCE | TOKEN_ADJUST_PRIVILEGES | TOKEN_ADJUST_GROUPS | TOKEN_ADJUST_DEFAULT | TOKEN_ADJUST_SESSIONID ) MAXIMUM_ALLOWED = 0x02000000 MANDATORY_LABEL_AUTHORITY = (ctypes.c_byte * 6)(0,0,0,0,0,16) def IsFilteredUACToken(hToken): tokenIsFiltered = False TokenInfLength = ctypes.wintypes.DWORD(0) if AccessToken.GetTokenIntegrityLevel(hToken) >= IntegrityLevel.High: return False GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevation, ctypes.c_void_p(0), TokenInfLength, ctypes.byref(TokenInfLength)) tokenElevationPtr = (ctypes.c_byte * TokenInfLength.value)() if not GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevation, ctypes.byref(tokenElevationPtr), TokenInfLength, ctypes.byref(TokenInfLength)): raise RunAsPyException(f"GetTokenInformation TokenElevation") tokenElevation = ctypes.cast(ctypes.pointer(tokenElevationPtr), ctypes.POINTER(TOKEN_ELEVATION)) if tokenElevation.contents.TokenIsElevated > 0: tokenIsFiltered = False else: TokenInfLength = ctypes.wintypes.DWORD(0) GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, ctypes.c_void_p(0), TokenInfLength, ctypes.byref(TokenInfLength)) tokenElevationTypePtr = (ctypes.c_byte * TokenInfLength.value)() if not GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenElevationType, ctypes.byref(tokenElevationTypePtr), TokenInfLength, ctypes.byref(TokenInfLength)): raise RunAsPyException("GetTokenInformation TokenElevationType") tokenElevationType = ctypes.cast(ctypes.pointer(tokenElevationTypePtr), ctypes.POINTER(TOKEN_ELEVATION_TYPE)) if tokenElevationType.contents.TokenElevationType == 3: tokenIsFiltered = True return tokenIsFiltered def GetTokenPrivileges(tHandle): privileges = [] TokenInfLength = ctypes.wintypes.DWORD(0) result = GetTokenInformation(tHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, ctypes.c_void_p(0), TokenInfLength, ctypes.byref(TokenInfLength)) TokenInformation = (ctypes.c_ubyte * TokenInfLength.value)() result = GetTokenInformation(tHandle, TOKEN_INFORMATION_CLASS.TokenPrivileges, ctypes.byref(TokenInformation), TokenInfLength, ctypes.byref(TokenInfLength)) if not result: raise RunAsPyException(f"GetTokenInformation") TokenPrivileges = ctypes.cast(ctypes.pointer(TokenInformation), ctypes.POINTER(TOKEN_PRIVILEGES)) for tokenPriv in range(0, TokenPrivileges.contents.PrivilegeCount): luid = TokenPrivileges.contents.Privileges[tokenPriv].Luid luidNameLen = ctypes.wintypes.DWORD(0) LookupPrivilegeName(ctypes.c_void_p(0), ctypes.byref(luid), ctypes.c_void_p(0), ctypes.byref(luidNameLen)) sb = (ctypes.c_char * luidNameLen.value)() result = LookupPrivilegeName(ctypes.c_void_p(0), ctypes.byref(luid), sb, ctypes.byref(luidNameLen)) if not result: raise RunAsPyException("LookupPrivilegeName") privilegeStatus = [ bytes(sb).decode()[:-1], convertAttributeToString(TokenPrivileges.contents.Privileges[tokenPriv].Attributes) ] privileges.append(privilegeStatus) return privileges def EnablePrivilege(privilege, token): sebLuid = LUID() tokenp = TOKEN_PRIVILEGES_2() tokenp.PrivilegeCount = 1 LookupPrivilegeValue(ctypes.c_void_p(0), ctypes.wintypes.LPCSTR(privilege.encode()), ctypes.byref(sebLuid)) tokenp.Luid = sebLuid tokenp.Attributes = AccessToken.SE_PRIVILEGE_ENABLED if not AdjustTokenPrivileges(token, ctypes.c_bool(False), ctypes.byref(tokenp), ctypes.wintypes.DWORD(0), ctypes.c_void_p(0), ctypes.c_void_p(0)): raise RunAsPyException(f"AdjustTokenPrivileges on privilege { privilege }") logging.info(f"AdjustTokenPrivileges on privilege { privilege } succeeded") def EnableAllPrivileges(token): for privilege in privileges: AccessToken.EnablePrivilege(privilege, token) def GetTokenIntegrityLevel(hToken): illevel = IntegrityLevel.Unknown cb = ctypes.wintypes.DWORD(0) GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, ctypes.c_void_p(None), ctypes.wintypes.DWORD(0), ctypes.byref(cb)) pb = (ctypes.c_char * cb.value)() if GetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, ctypes.byref(pb), cb, ctypes.byref(cb)): pSid = ctypes.c_void_p.from_address(ctypes.addressof(pb)) dwIntegrityLevel = GetSidSubAuthority(pSid, ctypes.wintypes.DWORD(GetSidSubAuthorityCount(pSid).contents.value - 1)) if dwIntegrityLevel.contents.value == AccessToken.SECURITY_MANDATORY_LOW_RID: return IntegrityLevel.Low elif dwIntegrityLevel.contents.value >= AccessToken.SECURITY_MANDATORY_MEDIUM_RID and dwIntegrityLevel.contents.value < AccessToken.SECURITY_MANDATORY_HIGH_RID: return IntegrityLevel.Medium elif dwIntegrityLevel.contents.value >= AccessToken.SECURITY_MANDATORY_HIGH_RID: return IntegrityLevel.High elif dwIntegrityLevel.contents.value >= AccessToken.SECURITY_MANDATORY_SYSTEM_RID: return IntegrityLevel.System return IntegrityLevel.Unknown return illevel def SetTokenIntegrityLevel(hToken, integrity): ret = False pSID = ctypes.c_void_p(0) tokenLabel = TOKEN_MANDATORY_LABEL() authoritySidStruct = SID_IDENTIFIER_AUTHORITY() authoritySidStruct.Value = AccessToken.MANDATORY_LABEL_AUTHORITY pLabelAuthority = (ctypes.c_ubyte * ctypes.sizeof(authoritySidStruct))() ctypes.memmove(pLabelAuthority, ctypes.byref(authoritySidStruct), ctypes.sizeof(pLabelAuthority)) result = AllocateAndInitializeSid( ctypes.byref(pLabelAuthority), ctypes.c_byte(1), ctypes.wintypes.DWORD(integrity), ctypes.wintypes.DWORD(0), ctypes.wintypes.DWORD(0), ctypes.wintypes.DWORD(0), ctypes.wintypes.DWORD(0), ctypes.wintypes.DWORD(0), ctypes.wintypes.DWORD(0), ctypes.wintypes.DWORD(0), ctypes.byref(pSID) ) tokenLabel.Label.Sid = pSID tokenLabel.Label.Attributes = TokenGroupAttributes.SE_GROUP_INTEGRITY labelSize = ctypes.sizeof(tokenLabel) pLabel = (ctypes.c_ubyte * labelSize)() ctypes.memmove(pLabel, ctypes.byref(tokenLabel), ctypes.sizeof(pLabel)) result = SetTokenInformation(hToken, TOKEN_INFORMATION_CLASS.TokenIntegrityLevel, ctypes.byref(pLabel), ctypes.wintypes.DWORD(labelSize)) if not result: raise RunAsPyException(f"[!] Failed to set the token's Integrity Level ({integrity})") else: ret = True return ret def CreateAnonymousPipeEveryoneAccess(hReadPipe, hWritePipe): sa = SECURITY_ATTRIBUTES() sa.nLength = ctypes.sizeof(sa) sa.lpSecurityDescriptor = ctypes.c_void_p(0) sa.bInheritHandle = True if CreatePipe(ctypes.byref(hReadPipe), ctypes.byref(hWritePipe), ctypes.byref(sa), ctypes.wintypes.DWORD(BUFFER_SIZE_PIPE)): return True return False def ParseCommonProcessInCommandline(commandline): if (commandline[0].lower() == "cmd" or commandline[0].lower() == "cmd.exe"): commandline[0] = os.environ['COMSPEC'] elif (commandline[0].lower() == "powershell" or commandline[0].lower() == "powershell.exe"): commandline[0] = f"{os.environ['WINDIR']}\\System32\\WindowsPowerShell\\v1.0\\powershell.exe" return " ".join(commandline) def CheckAvailableUserLogonType(username, password, domainName, logonType, logonProvider): hTokenCheck1 = ctypes.wintypes.HANDLE(0) if not LogonUser(username, domainName, password, logonType, logonProvider.value, ctypes.byref(hTokenCheck1)): if ctypes.GetLastError() == ERROR_LOGON_TYPE_NOT_GRANTED: availableLogonType = 0 for logonTypeTry in [LOGON32_LOGON_SERVICE, LOGON32_LOGON_BATCH, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_LOGON_NETWORK, LOGON32_LOGON_INTERACTIVE]: hTokenCheck2 = ctypes.c_void_p(0) if LogonUser(username, domainName, password, logonTypeTry, logonProvider, hTokenCheck2): availableLogonType = logonTypeTry if AccessToken.GetTokenIntegrityLevel(hTokenCheck2) > IntegrityLevel.Medium: availableLogonType = logonTypeTry CloseHandle(hTokenCheck2) break if hTokenCheck2.value != 0: CloseHandle(hTokenCheck2) if availableLogonType != 0: raise RunAsPyException(f"Selected logon type '{ logonType }' is not granted to the user '{ username.decode() }'. Use available logon type '{ availableLogonType.value }'.") else: raise RunAsPyException(f"LogonUser") raise RunAsPyException(f"LogonUser") if hTokenCheck1.value != 0: CloseHandle(hTokenCheck1) def GetProcessFunction(createProcessFunction): if createProcessFunction == 0: return "CreateProcessAsUserW()" elif createProcessFunction == 1: return "CreateProcessWithTokenW()" else: return "CreateProcessWithLogonW()" def GetUserSid(domain, username): err = 0 Sid = ctypes.c_byte() cbSid = ctypes.wintypes.DWORD(0) referencedDomainName = ctypes.wintypes.LPSTR(None) cchReferencedDomainName = ctypes.wintypes.DWORD(0) if domain and domain != b".": fqan = domain + b"\\" + username else: fqan = username fqan_buffer = ctypes.create_string_buffer(fqan, len(fqan) + 1) if not LookupAccountName(None, fqan_buffer, ctypes.byref(Sid), ctypes.byref(cbSid), referencedDomainName, ctypes.byref(cchReferencedDomainName), ctypes.byref(SID_NAME_USE.SidTypeUser)): if ctypes.GetLastError() in [ERROR_INVALID_FLAGS, ERROR_INSUFFICIENT_BUFFER]: Sid = (ctypes.c_byte * cbSid.value)() referencedDomainName = ctypes.create_string_buffer(cchReferencedDomainName.value) if not LookupAccountName(None, fqan_buffer, ctypes.byref(Sid), ctypes.byref(cbSid), referencedDomainName, ctypes.byref(cchReferencedDomainName), ctypes.byref(SID_NAME_USE.SidTypeUser)): err = ctypes.GetLastError() else: raise RunAsPyException(f"The username { fqan } has not been found. LookupAccountName") if err != 0: raise RunAsPyException(f"The username { fqan } has not been found. LookupAccountName") return Sid def DefaultCreateProcessFunction(): currentTokenHandle = ctypes.wintypes.HANDLE(0) SeAssignPrimaryTokenPrivilegeAssigned = False SeImpersonatePrivilegeAssigned = False if not OpenProcessToken(ctypes.wintypes.HANDLE(-1), ctypes.wintypes.DWORD(AccessToken.TOKEN_QUERY), ctypes.byref(currentTokenHandle)): raise RunAsPyException("Failed to obtain token") privs = AccessToken.GetTokenPrivileges(currentTokenHandle) for priv in privs: if priv[0] == "SeAssignPrimaryTokenPrivilege" and AccessToken.GetTokenIntegrityLevel(currentTokenHandle) >= IntegrityLevel.Medium: SeAssignPrimaryTokenPrivilegeAssigned = True elif priv[0] == "SeImpersonatePrivilege" and AccessToken.GetTokenIntegrityLevel(currentTokenHandle) >= IntegrityLevel.High: SeImpersonatePrivilegeAssigned = True if SeAssignPrimaryTokenPrivilegeAssigned: createProcessFunction = 0 elif SeImpersonatePrivilegeAssigned: createProcessFunction = 1 else: createProcessFunction = 2 return createProcessFunction class WindowStationDACL(object): def __init__(self): self.hWinsta = ctypes.c_void_p(0) self.hDesktop = ctypes.c_void_p(0) self.userSid = ctypes.c_void_p(0) def AddAllowedAceToDACL(self, pDacl, mask, aceFlags, aceSize): offset = ctypes.sizeof(ACCESS_ALLOWED_ACE) - ctypes.sizeof(ctypes.c_uint) AceHeader = ACE_HEADER() AceHeader.AceType = ACCESS_ALLOWED_ACE_TYPE AceHeader.AceFlags = aceFlags AceHeader.AceSize = aceSize pNewAcePtr = (ctypes.c_ubyte * aceSize)() pNewAceStruct = ACCESS_ALLOWED_ACE() pNewAceStruct.Header = AceHeader pNewAceStruct.Mask = mask sidStartPtr = ctypes.addressof(pNewAcePtr) + offset ctypes.memmove(pNewAcePtr, ctypes.byref(pNewAceStruct), ctypes.sizeof(pNewAceStruct)) if not CopySid(ctypes.wintypes.DWORD(GetLengthSid(self.userSid)), ctypes.c_void_p(sidStartPtr), ctypes.byref(self.userSid)): raise RunAsPyException("CopySid") if not AddAce(ctypes.byref(pDacl), ctypes.wintypes.DWORD(ACL_REVISION), ctypes.wintypes.DWORD(MAXDWORD), ctypes.byref(pNewAcePtr), ctypes.wintypes.DWORD(aceSize)): raise RunAsPyException("AddAce") def AddAce(self, target): if target not in self.__dict__: raise RunAsPyException(f"{target} not an attribute of WinStationDACL object") pSd = ctypes.c_void_p(0) pDacl = ctypes.c_void_p(0) cbSd = ctypes.wintypes.DWORD(0) fDaclExist = ctypes.c_bool(False) fDaclPresent = ctypes.c_bool(False) aclSizeInfo = ACL_SIZE_INFORMATION() si = SECURITY_INFORMATION.DACL_SECURITY_INFORMATION if not GetUserObjectSecurity(ctypes.wintypes.HANDLE(self.__dict__[target]), ctypes.byref(si), ctypes.byref(pSd), ctypes.wintypes.DWORD(0), ctypes.byref(cbSd)): if ctypes.GetLastError() != ERROR_INSUFFICIENT_BUFFER: raise RunAsPyException(f"GetUserObjectSecurity 1 size") pSd = (ctypes.c_ubyte * cbSd.value)() if not GetUserObjectSecurity(ctypes.wintypes.HANDLE(self.__dict__[target]), ctypes.byref(si), ctypes.byref(pSd), cbSd, ctypes.byref(cbSd)): raise RunAsPyException(f"GetUserObjectSecurity 2") if not GetSecurityDescriptorDacl(ctypes.byref(pSd), ctypes.byref(fDaclPresent), ctypes.byref(pDacl), ctypes.byref(fDaclExist)): raise RunAsPyException(f"GetSecurityDescriptorDacl") if not pDacl: cbDacl = 0 else: if not GetAclInformation(pDacl, ctypes.byref(aclSizeInfo), ctypes.wintypes.DWORD(ctypes.sizeof(aclSizeInfo)), ACL_INFORMATION_CLASS.AclSizeInformation): raise RunAsPyException(f"GetAclInformation") cbDacl = aclSizeInfo.AclBytesInUse pNewSd = (ctypes.c_byte * cbSd.value )() if not InitializeSecurityDescriptor(ctypes.byref(pNewSd), ctypes.wintypes.DWORD(SECURITY_DESCRIPTOR_REVISION)): raise RunAsPyException(f"InitializeSecurityDescriptor") cbNewAce = ctypes.sizeof(ACCESS_ALLOWED_ACE) + GetLengthSid(self.userSid) - ctypes.sizeof(ctypes.c_uint) if not cbDacl: cbNewDacl = 8 + ((cbNewAce*2) if target == "hWinsta" else cbNewAce) else: cbNewDacl = cbDacl + ((cbNewAce*2) if target == "hWinsta" else cbNewAce) pNewDacl = (ctypes.c_byte * cbNewDacl)() if not InitializeAcl(ctypes.byref(pNewDacl), ctypes.wintypes.DWORD(cbNewDacl), ctypes.wintypes.DWORD(ACL_REVISION)): raise RunAsPyException(f"InitializeAcl") if fDaclPresent: for dwIndex in range(0, aclSizeInfo.AceCount): pTempAce = ctypes.c_void_p(0) if not GetAce(pDacl, ctypes.wintypes.DWORD(dwIndex), ctypes.byref(pTempAce)): raise RunAsPyException(f"GetAce") pTempAceStruct = ctypes.cast(pTempAce, ctypes.POINTER(ACE_HEADER)) if not AddAce(ctypes.byref(pNewDacl), ctypes.wintypes.DWORD(ACL_REVISION), ctypes.wintypes.DWORD(MAXDWORD), pTempAce, ctypes.wintypes.DWORD(pTempAceStruct.contents.AceSize)): raise RunAsPyException("AddAce") if target == "hWinsta": self.AddAllowedAceToDACL(pNewDacl, ACCESS_MASK.GENERIC_ACCESS, (CONTAINER_INHERIT_ACE | INHERIT_ONLY_ACE | OBJECT_INHERIT_ACE), cbNewAce) self.AddAllowedAceToDACL(pNewDacl, ACCESS_MASK.WINSTA_ALL, NO_PROPAGATE_INHERIT_ACE, cbNewAce) elif target == "hDesktop": if not AddAccessAllowedAce(ctypes.byref(pNewDacl), ctypes.wintypes.DWORD(ACL_REVISION), ctypes.wintypes.DWORD(ACCESS_MASK.DESKTOP_ALL), self.userSid): raise RunAsPyException("AddAccessAllowedAce") if not SetSecurityDescriptorDacl(ctypes.byref(pNewSd), ctypes.c_bool(True), ctypes.byref(pNewDacl), ctypes.c_bool(False)): raise RunAsPyException("SetSecurityDescriptorDacl") if not SetUserObjectSecurity(ctypes.wintypes.HANDLE(self.__dict__[target]), ctypes.byref(si), ctypes.byref(pNewSd)): raise RunAsPyException("SetUserObjectSecurity") def AddAclToActiveWindowStation(self, domain, username, logonType): desktop = ctypes.create_string_buffer(b"Default", 8) lengthNeeded = ctypes.wintypes.DWORD(0) hWinstaSave = GetProcessWindowStation() stationNameBytes = (ctypes.c_byte * 256)() if not hWinstaSave: raise RunAsPyException(f"GetProcessWindowStation") if not GetUserObjectInformation(ctypes.wintypes.HANDLE(hWinstaSave), ctypes.c_int(UOI_NAME), ctypes.byref(stationNameBytes), ctypes.wintypes.DWORD(256), ctypes.byref(lengthNeeded)): raise RunAsPyException(f"GetUserObjectInformation") stationName = bytes(stationNameBytes)[:lengthNeeded.value - 1] if logonType != 9: self.hWinsta = OpenWindowStation(stationName, ctypes.c_bool(False), (READ_CONTROL | WRITE_DAC)) if not self.hWinsta: raise RunAsPyException("OpenWindowStation") if not SetProcessWindowStation(ctypes.wintypes.HANDLE(self.hWinsta)): raise RunAsPyException("SetProcessWindowStation hWinsta") self.hDesktop = OpenDesktop(ctypes.byref(desktop), ctypes.wintypes.DWORD(0), ctypes.c_bool(False), ctypes.wintypes.DWORD(READ_CONTROL | WRITE_DAC | DESKTOP_WRITEOBJECTS | DESKTOP_READOBJECTS)) if not SetProcessWindowStation(ctypes.wintypes.HANDLE(hWinstaSave)): raise RunAsPyException("SetProcessWindowStation hWinstaSave") if not self.hWinsta: raise RunAsPyException("OpenDesktop") self.userSid = GetUserSid(domain, username) self.AddAce('hWinsta') self.AddAce('hDesktop') return stationName + b"\\Default" class RunAsPy(): def __init__(self): self.hOutputRead = ctypes.c_void_p() self.hOutputWrite = ctypes.c_void_p() self.hErrorWrite = ctypes.c_void_p() self.socket = ctypes.c_void_p() self.stationDaclObj = None self.startupInfo = STARTUPINFO() self.hTokenPreviousImpersonatingThread = ctypes.c_void_p() self.logonTypeNotFiltered = 0 def ImpersonateLoggedOnUserWithProperIL(self, hToken): TokenImpersonation = 2 hTokenDuplicateLocal = ctypes.c_void_p(0) pHandle = ctypes.wintypes.HANDLE(0) current_thread = GetCurrentThread() if not OpenThreadToken(ctypes.wintypes.HANDLE(current_thread), ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.c_bool(False), ctypes.byref(pHandle)): error = ctypes.GetLastError() if error != ERROR_NO_TOKEN: raise RunAsPyException(f"Failed to obtain token: { error }") else: self.hTokenPreviousImpersonatingThread = pHandle if not DuplicateTokenEx(hToken, ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.c_void_p(0), SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ctypes.c_int(TokenImpersonation), ctypes.byref(hTokenDuplicateLocal)): raise RunAsPyException(f"DuplicateTokenEx") pToken = ctypes.wintypes.HANDLE(0) if not OpenProcessToken(ctypes.wintypes.HANDLE(-1), ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.byref(pToken)): raise RunAsPyException("Failed to obtain token") if AccessToken.GetTokenIntegrityLevel(pToken) < AccessToken.GetTokenIntegrityLevel(hTokenDuplicateLocal): AccessToken.SetTokenIntegrityLevel(hTokenDuplicateLocal, AccessToken.GetTokenIntegrityLevel(pToken)) ImpersonateLoggedOnUser(hTokenDuplicateLocal) return hTokenDuplicateLocal def IsLimitedUserLogon(self, hToken, username, domainName, password): isLimitedUserLogon = False isTokenUACFiltered = AccessToken.IsFilteredUACToken(hToken) hTokenNetwork = ctypes.c_void_p(0) hTokenService = ctypes.c_void_p(0) hTokenBatch = ctypes.c_void_p(0) if isTokenUACFiltered: self.logonTypeNotFiltered = LOGON32_LOGON_NETWORK_CLEARTEXT isLimitedUserLogon = True else: userTokenIL = AccessToken.GetTokenIntegrityLevel(hToken) if LogonUser(username, domainName, password, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT, ctypes.byref(hTokenNetwork)) and userTokenIL < AccessToken.GetTokenIntegrityLevel(hTokenNetwork.value): isLimitedUserLogon = True self.logonTypeNotFiltered = LOGON32_LOGON_NETWORK_CLEARTEXT.value elif not isLimitedUserLogon and LogonUser(username, domainName, password, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, ctypes.byref(hTokenNetwork)) and userTokenIL < AccessToken.GetTokenIntegrityLevel(hTokenService): isLimitedUserLogon = True self.logonTypeNotFiltered = LOGON32_LOGON_SERVICE elif not isLimitedUserLogon and LogonUser(username, domainName, password, LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, ctypes.byref(hTokenBatch)) and userTokenIL < AccessToken.GetTokenIntegrityLevel(hTokenBatch): isLimitedUserLogon = True self.logonTypeNotFiltered = LOGON32_LOGON_BATCH if hTokenNetwork.value: CloseHandle(hTokenNetwork) if hTokenService.value: CloseHandle(hTokenService) if hTokenBatch.value: CloseHandle(hTokenBatch) return isLimitedUserLogon def ConnectRemote(self, remote): host, port = remote.split(":") try: port = int(port) except: raise RunAsPyException(f"Specified port is invalid: { port }") data = WSADATA() if WSAStartup(2 << 8 | 2, ctypes.byref(data)): raise RunAsPyException(f"WSAStartup failed with error code: { ctypes.GetLastError() }") sock = WSASocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP, ctypes.c_void_p(0), ctypes.wintypes.DWORD(0), ctypes.wintypes.DWORD(0)) if sock == 0xffff: raise RunAsPyException(f"Failed to create socket: { ctypes.GetLastError() }") sockinfo = SOCKADDR_IN() sockinfo.sin_family = 2 sockinfo.sin_addr = struct.unpack("<L", socket.inet_aton(host))[0] sockinfo.sin_port = socket.htons(port) if connect(ctypes.wintypes.HANDLE(sock), ctypes.byref(sockinfo), ctypes.c_int(ctypes.sizeof(sockinfo))): raise RunAsPyException(f"WSAConnect failed with error code: { ctypes.GetLastError() }") return sock def IsUserProfileCreated(self, username, password, domainName, logonType): result = False hToken = ctypes.c_void_p(0) logonProvider = LOGON32_PROVIDER_DEFAULT if logonType == LOGON32_LOGON_NEW_CREDENTIALS: logonProvider = LOGON32_PROVIDER_WINNT50 result = LogonUser(username, domainName, password, ctypes.wintypes.DWORD(logonType), logonProvider, ctypes.byref(hToken)) if not result: raise RunAsPyException("LogonUser") hTokenDuplicate = self.ImpersonateLoggedOnUserWithProperIL(hToken) try: dwSize = ctypes.wintypes.DWORD(0) GetUserProfileDirectory(hToken, ctypes.wintypes.LPSTR(b""), dwSize) profileDir = ctypes.wintypes.LPSTR(b" " * dwSize.value) GetUserProfileDirectory(hToken, profileDir, dwSize) except: result = False self.RevertToSelfCustom() CloseHandle(hTokenDuplicate) return result def CreateProcessWithLogonWUacBypass(self, logonType, logonFlags, username, domainName, password, processPath, commandLine, processInfo): result = False hToken = ctypes.c_void_p(0) pToken = ctypes.wintypes.HANDLE(0) hCurrentProcess = ctypes.wintypes.HANDLE(GetCurrentProcess()) if not LogonUser(username, domainName, password, ctypes.wintypes.DWORD(logonType), LOGON32_PROVIDER_DEFAULT, ctypes.byref(hToken)): raise RunAsPyException(f"CreateProcessWithLogonWUacBypass: LogonUser") if not OpenProcessToken(ctypes.wintypes.HANDLE(-1), ctypes.wintypes.DWORD(AccessToken.MAXIMUM_ALLOWED), ctypes.byref(pToken)): raise RunAsPyException("Failed to obtain token") AccessToken.SetTokenIntegrityLevel(hToken, AccessToken.GetTokenIntegrityLevel(pToken)) SetSecurityInfo(ctypes.wintypes.HANDLE(-1), SE_OBJECT_TYPE.SE_KERNEL_OBJECT, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, ctypes.c_void_p(0), ctypes.c_void_p(0), ctypes.c_void_p(0), ctypes.c_void_p(0)) if not DuplicateHandle(hCurrentProcess, hToken, hCurrentProcess, ctypes.byref(hCurrentProcess), ctypes.wintypes.DWORD(0), True, DUPLICATE_SAME_ACCESS): raise RunAsPyException(f"Failed to duplicate handle: { hCurrentProcess } ") result = CreateProcessWithLogonW( username.decode(), domainName.decode(), password.decode(), logonFlags.value | LOGON_NETCREDENTIALS_ONLY, processPath.decode() if processPath else processPath, commandLine, CREATE_NO_WINDOW, None, None, ctypes.byref(self.startupInfo), ctypes.byref(processInfo) ) return result def ReadOutputFromPipe(self, hReadPipe): dwBytesRead = ctypes.wintypes.DWORD(0) buffer = (ctypes.c_byte * BUFFER_SIZE_PIPE)() output = "" hResult = False while not hResult: hResult = ReadFile(hReadPipe, ctypes.byref(buffer), ctypes.wintypes.DWORD(BUFFER_SIZE_PIPE), ctypes.byref(dwBytesRead), ctypes.c_void_p(0)) if not hResult and ctypes.GetLastError() != ERROR_MORE_DATA: break output += bytes(buffer[:dwBytesRead.value]).decode().replace("\n","") if not hResult: logging.info("No output received from the process.") return output def RevertToSelfCustom(self): RevertToSelf() if self.hTokenPreviousImpersonatingThread: ImpersonateLoggedOnUser(self.hTokenPreviousImpersonatingThread) def GetUserEnvironmentBlock(self, hToken, username, forceUserProfileCreation, userProfileExists): result = False profileInfo = PROFILEINFO() lpEnvironment = ctypes.c_void_p(0) hTokenDuplicate = ctypes.c_void_p(0) if forceUserProfileCreation or userProfileExists: profileInfo.dwSize = ctypes.sizeof(profileInfo) profileInfo.lpUserName = username result = LoadUserProfile(hToken, ctypes.byref(profileInfo)) if not result and ctypes.GetLastError() == 1314: logging.warning("LoadUserProfile failed due to insufficient permissions") hTokenDuplicate = self.ImpersonateLoggedOnUserWithProperIL(hToken) try: CreateEnvironmentBlock(ctypes.byref(lpEnvironment), hToken, ctypes.c_bool(False)) except: result = False self.RevertToSelfCustom() CloseHandle(hTokenDuplicate) if result and (forceUserProfileCreation or userProfileExists): UnloadUserProfile(hToken, profileInfo.hProfile) def RunasRemoteImpersonation(self, username, domainName, password, logonType, logonProvider, commandLine, processInfo): TokenImpersonation = 2 hToken = ctypes.c_void_p(0) lpEnvironment = ctypes.c_void_p(0) hTokenDupImpersonation = ctypes.c_void_p(0) if not LogonUser(username, domainName, password, logonType, logonProvider, hToken): raise RunAsPyException(f"LogonUser") if self.IsLimitedUserLogon(hToken, username, domainName, password): logging.warning(f"Logon for user '{ username.decode() }' is limited. Use the --logon-type value '{ self.logonTypeNotFiltered.value }' to obtain a more privileged token") if not DuplicateTokenEx(hToken, ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.c_void_p(0), SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ctypes.c_int(TokenImpersonation), ctypes.byref(hTokenDupImpersonation)): raise RunAsPyException(f"DuplicateTokenEx") pToken = ctypes.wintypes.HANDLE(0) if not OpenProcessToken(ctypes.wintypes.HANDLE(GetCurrentProcess()), ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.byref(pToken)): raise RunAsPyException("Failed to obtain token") if AccessToken.GetTokenIntegrityLevel(pToken) < AccessToken.GetTokenIntegrityLevel(hTokenDupImpersonation): AccessToken.SetTokenIntegrityLevel(hTokenDupImpersonation, AccessToken.GetTokenIntegrityLevel(pToken)) AccessToken.EnableAllPrivileges(hTokenDupImpersonation) if not CreateEnvironmentBlock(ctypes.byref(lpEnvironment), hToken, ctypes.c_bool(False)): logging.warning(f"Unable to create environment block") if not CreateProcessW( None, commandLine, None, None, True, CREATE_NO_WINDOW | CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT, lpEnvironment, (os.environ["SystemRoot"] + "\\System32"), ctypes.byref(self.startupInfo), ctypes.byref(processInfo) ): raise RunAsPyException(f"CreateProcess") hTokenProcess = ctypes.c_void_p(0) if not OpenProcessToken(ctypes.wintypes.HANDLE(processInfo.process), ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.byref(hTokenProcess)): raise RunAsPyException(f"OpenProcessToken") AccessToken.SetTokenIntegrityLevel(hTokenProcess, AccessToken.GetTokenIntegrityLevel(hTokenDupImpersonation)) SetSecurityInfo(processInfo.process, SE_OBJECT_TYPE.SE_KERNEL_OBJECT, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, ctypes.c_void_p(0), ctypes.c_void_p(0), ctypes.c_void_p(0), ctypes.c_void_p(0)) SetSecurityInfo(hTokenProcess, SE_OBJECT_TYPE.SE_KERNEL_OBJECT, SECURITY_INFORMATION.DACL_SECURITY_INFORMATION, ctypes.c_void_p(0), ctypes.c_void_p(0), ctypes.c_void_p(0), ctypes.c_void_p(0)) if not SetThreadToken(ctypes.byref(ctypes.wintypes.HANDLE(processInfo.thread)), hTokenDupImpersonation): raise RunAsPyException(f"SetThreadToken") ResumeThread(ctypes.wintypes.HANDLE(processInfo.thread)) CloseHandle(hToken) CloseHandle(hTokenDupImpersonation) CloseHandle(hTokenProcess) def RunasCreateProcessAsUserW(self, username, domainName, password, logonType, logonProvider, commandLine, forceUserProfileCreation, userProfileExists, processInfo): hToken = ctypes.c_void_p(0) TokenPrimary = 2 hTokenDuplicate = ctypes.c_void_p(0) lpEnvironment = ctypes.c_void_p(0) if not LogonUser(username, domainName, password, logonType, logonProvider, hToken): raise RunAsPyException(f"LogonUser") if not DuplicateTokenEx(hToken, ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.c_void_p(0), SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ctypes.c_int(TokenPrimary), ctypes.byref(hTokenDuplicate)): raise RunAsPyException(f"TokenDuplicateEx") if self.IsLimitedUserLogon(hTokenDuplicate, username, domainName, password): logging.warning(f"Logon for user '{ username.decode() }' is limited. Use the --logon-type value '{ self.logonTypeNotFiltered.value }' to obtain a more privileged token") lpEnvironment = self.GetUserEnvironmentBlock(hTokenDuplicate, username, forceUserProfileCreation, userProfileExists) pToken = ctypes.wintypes.HANDLE(0) if not OpenProcessToken(ctypes.wintypes.HANDLE(GetCurrentProcess()), ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.byref(pToken)): raise RunAsPyException("Failed to obtain token") AccessToken.EnablePrivilege("SeAssignPrimaryTokenPrivilege", pToken) AccessToken.EnableAllPrivileges(hTokenDuplicate) if not CreateProcessAsUser(hTokenDuplicate, ctypes.c_void_p(None), ctypes.wintypes.LPCSTR(commandLine.encode()), ctypes.c_void_p(0), ctypes.c_void_p(0), ctypes.c_bool(True), ctypes.wintypes.DWORD(CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT), ctypes.c_void_p(lpEnvironment), ctypes.wintypes.LPCSTR((os.environ["SystemRoot"] + "\\System32").encode()), ctypes.byref(self.startupInfo), ctypes.byref(processInfo)): raise RunAsPyException(f"CreateProcessAsUser") if lpEnvironment: DestroyEnvironmentBlock(lpEnvironment) CloseHandle(hToken) CloseHandle(hTokenDuplicate) def RunasCreateProcessWithTokenW(self, username, domainName, password, commandLine, logonType, logonFlags, logonProvider, processInfo): TokenPrimary = 1 hToken = ctypes.c_void_p(0) hTokenDuplicate = ctypes.c_void_p(0) if not LogonUser(username, domainName, password, logonType, logonProvider, hToken): raise RunAsPyException("LogonUser") if not DuplicateTokenEx(hToken, ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.c_void_p(0), SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, ctypes.c_int(TokenPrimary), ctypes.byref(hTokenDuplicate)): raise RunAsPyException("DuplicatetokenEx") if self.IsLimitedUserLogon(hTokenDuplicate, username, domainName, password): logging.warning(f"Logon for user '{ username.decode() }' is limited. Use the --logon-type value '{ self.logonTypeNotFiltered.value }' to obtain a more privileged token") pToken = ctypes.wintypes.HANDLE(0) if not OpenProcessToken(ctypes.wintypes.HANDLE(GetCurrentProcess()), ctypes.wintypes.DWORD(AccessToken.TOKEN_ALL_ACCESS), ctypes.byref(pToken)): raise RunAsPyException("Failed to obtain token") AccessToken.EnablePrivilege("SeImpersonatePrivilege", pToken) AccessToken.EnableAllPrivileges(hTokenDuplicate) #CreateProcessWithTokenW(hTokenDuplicate, ctypes.c_ulong(1), None, ctypes.wintypes.LPWSTR(sys.argv[1]), ctypes.wintypes.DWORD(CREATE_NO_WINDOW), None, None, ctypes.byref(self.startupInfo), ctypes.byref(processInfo)) if not CreateProcessWithTokenW(hTokenDuplicate, logonFlags, None, ctypes.wintypes.LPWSTR(commandLine.decode()), ctypes.wintypes.DWORD(CREATE_NO_WINDOW), None, None, ctypes.byref(self.startupInfo), ctypes.byref(processInfo)): raise RunAsPyException("CreateProcessWithTokenW") CloseHandle(hToken) CloseHandle(hTokenDuplicate) def RunasCreateProcessWithLogonW(self, username, domainName, password, logonType, logonFlags, commandLine, bypassUac, startupInfo, processInfo): if logonType == LOGON32_LOGON_NEW_CREDENTIALS.value: if not CreateProcessWithLogonW(username.decode(), domainName.decode(), password.decode(), ctypes.wintypes.DWORD(LOGON_NETCREDENTIALS_ONLY), None, commandLine, CREATE_NO_WINDOW, None, None, ctypes.byref(self.startupInfo), ctypes.byref(processInfo)): raise RunAsPyException(f"CreateProcessWithLogonW logon type 9") elif bypassUac: if logonType in [LOGON32_LOGON_NETWORK.value, LOGON32_LOGON_BATCH.value, LOGON32_LOGON_SERVICE.value, LOGON32_LOGON_NETWORK_CLEARTEXT.value]: logonTypeBypassUac = logonType else: logonTypeBypassUac = LOGON32_LOGON_NETWORK_CLEARTEXT.value if not self.CreateProcessWithLogonWUacBypass(logonTypeBypassUac, logonFlags, username, domainName, password, None, commandLine, processInfo): raise RunAsPyException(f"CreateProcessWithLogonWUacBypass") else: hTokenUacCheck = ctypes.c_void_p(0) if logonType != LOGON32_LOGON_INTERACTIVE.value: logging.warning(f"The function CreateProcessWithLogonW is not compatible with the requested logon type '{ logonType }'. Reverting to the Interactive logon type '2'. To force a specific logon type, use the flag combination --remote-impersonation and --logon-type.") CheckAvailableUserLogonType(username, password, domainName, LOGON32_LOGON_INTERACTIVE.value, LOGON32_PROVIDER_DEFAULT) if not LogonUser(username, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, hTokenUacCheck): raise RunAsPyException("LogonUser") if self.IsLimitedUserLogon(hTokenUacCheck, username, domainName, password): logging.warning(f"The logon for user '{ username.decode() }' is limited. Use the flag combination --bypass-uac and --logon-type '{ self.logonTypeNotFiltered.value }' to obtain a more privileged token.") CloseHandle(hTokenUacCheck) if not CreateProcessWithLogonW(username.decode(), domainName.decode(), password.decode(), logonFlags, None, commandLine, CREATE_NO_WINDOW, None, None, ctypes.byref(self.startupInfo), ctypes.byref(processInfo)): raise RunAsPyException(f"CreateProcessWithLogonW logon type 2") def RunasSetupStdHandlesForProcess(self, processTimeout, remote): self.hOutputWrite = ctypes.c_void_p(0) self.hErrorWrite = ctypes.c_void_p(0) self.hOutputRead = ctypes.c_void_p(0) hOutputReadTmpLocal = ctypes.c_void_p(0) self.socket = ctypes.c_void_p(0) if processTimeout > 0: hCurrentProcess = ctypes.wintypes.HANDLE(-1) if not CreateAnonymousPipeEveryoneAccess(hOutputReadTmpLocal, self.hOutputWrite): raise RunAsPyException("CreatePipe") if not DuplicateHandle(hCurrentProcess, self.hOutputWrite, hCurrentProcess, ctypes.byref(self.hErrorWrite), ctypes.wintypes.DWORD(0), True, DUPLICATE_SAME_ACCESS): raise RunAsPyException("DuplicateHandle stderr write pipe") if not DuplicateHandle(hCurrentProcess, hOutputReadTmpLocal, hCurrentProcess, ctypes.byref(self.hOutputRead), ctypes.wintypes.DWORD(0), False, DUPLICATE_SAME_ACCESS): raise RunAsPyException("DuplicateHandle stdout read pipe") CloseHandle(hOutputReadTmpLocal) hOutputReadTmpLocal = ctypes.c_void_p(0) PIPE_NOWAIT = ctypes.wintypes.DWORD(0x00000001) if not SetNamedPipeHandleState(self.hOutputRead, ctypes.byref(PIPE_NOWAIT), ctypes.c_void_p(0), ctypes.c_void_p(0)): raise RunAsPyException("SetNamedPipeHandleState") self.startupInfo.dwFlags = Startf_UseStdHandles self.startupInfo.hStdOutput = self.hOutputWrite self.startupInfo.hStdError = self.hErrorWrite elif remote != None: self.socket = self.ConnectRemote(remote) self.startupInfo.dwFlags = Startf_UseStdHandles self.startupInfo.hStdInput = self.socket self.startupInfo.hStdOutput = self.socket self.startupInfo.hStdError = self.socket def RunAs(self, username, password, cmd, domainName, processTimeout, logonType, createProcessFunction, remote, forceUserProfileCreation, bypassUac, remoteImpersonation): if not domainName: domainName = "." username = bytes(username.encode()) password = bytes(password.encode()) domainName = bytes(domainName.encode()) commandLine = ParseCommonProcessInCommandline(cmd) logonProvider = LOGON32_PROVIDER_DEFAULT self.startupInfo.cb = ctypes.sizeof(self.startupInfo) processInfo = PROCESS_INFORMATION() self.RunasSetupStdHandlesForProcess(processTimeout, remote) self.stationDaclObj = WindowStationDACL() desktopName = self.stationDaclObj.AddAclToActiveWindowStation(domainName, username, logonType) self.startupInfo.lpDesktop = ctypes.wintypes.LPWSTR(desktopName.decode()) if logonType == LOGON32_LOGON_NEW_CREDENTIALS.value: logonProvider = LOGON32_PROVIDER_WINNT50 if not domainName: domainName = b"." CheckAvailableUserLogonType(username, password, domainName, logonType, logonProvider) if remoteImpersonation: self.RunasRemoteImpersonation(username, domainName, password, logonType, logonProvider, commandLine, processInfo) else: logonFlags = ctypes.c_uint32(0) userProfileExists = self.IsUserProfileCreated(username, password, domainName, logonType) if userProfileExists or forceUserProfileCreation: logonFlags = LOGON_WITH_PROFILE elif logonType != LOGON32_LOGON_NEW_CREDENTIALS.value and not forceUserProfileCreation and not userProfileExists: logging.warning(f"[*] Warning: User profile directory for user { username } does not exist. Use --force-profile if you want to force the creation.") if createProcessFunction == 2: self.RunasCreateProcessWithLogonW(username, domainName, password, logonType, logonFlags, commandLine, bypassUac, self.startupInfo, processInfo) else: if bypassUac: raise RunAsPyException(f"The flag --bypass-uac is not compatible with {GetProcessFunction(createProcessFunction)} but only with --function '2' (CreateProcessWithLogonW)", showError=False) if createProcessFunction == 0: self.RunasCreateProcessAsUserW(username, domainName, password, logonType, logonProvider, commandLine, forceUserProfileCreation, userProfileExists, processInfo) elif createProcessFunction == 1: self.RunasCreateProcessWithTokenW(username, domainName, password, commandLine.encode(), logonType, logonFlags, logonProvider, processInfo) output = "" if processTimeout > 0: CloseHandle(self.hOutputWrite) CloseHandle(self.hErrorWrite) self.hOutputWrite = ctypes.wintypes.DWORD(0) self.hErrorWrite = ctypes.wintypes.DWORD(0) WaitForSingleObject(processInfo.process, processTimeout) output += f"{self.ReadOutputFromPipe(self.hOutputRead)}" else: sessionId = ctypes.wintypes.DWORD() hResult = ProcessIdToSessionId(ctypes.wintypes.DWORD(GetCurrentProcessId()), ctypes.byref(sessionId)) if not hResult: raise SystemError(f"[!] Error encountered when obtaining session id: {hResult} ({ctypes.GetLastError()})") if remoteImpersonation: logging.info(f"Running in session { sessionId } with process function 'Remote Impersonation'") else: logging.info(f"Running in session { sessionId } with process function { GetProcessFunction(createProcessFunction)}") logging.info(f"Using Station\\Desktop: { desktopName }") logging.info(f"Async process '{ commandLine }' with pid { processInfo.processId } created in background.") CloseHandle(processInfo.process) CloseHandle(processInfo.thread) self.CleanupHandles() return output def CleanupHandles(self): if self.hOutputRead.value: CloseHandle(self.hOutputRead) if self.hOutputWrite.value: CloseHandle(self.hOutputWrite) if self.hErrorWrite: CloseHandle(self.hErrorWrite) if self.socket: closesocket(self.socket) self.hOutputRead = ctypes.c_void_p(0) self.hOutputWrite = ctypes.c_void_p(0) self.hErrorWrite = ctypes.c_void_p(0) self.socket = ctypes.c_void_p(0) self.hTokenPreviousImpersonatingThread = ctypes.c_void_p(0) self.stationDaclObj = None def Runas(username=None, password=None, cmd=None, domainName=None, processTimeout=120000, logonType=2, createProcessFunction=0, remote=None, forceUserProfileCreation=False, bypassUac=False, remoteImpersonation=False, verbose=False): if verbose: logging.getLogger().setLevel(logging.INFO) log_handler = logging.StreamHandler() log_handler.setLevel(logging.INFO) log_handler.setFormatter(runas_logging_formatter()) logging.getLogger().addHandler(log_handler) invoker = RunAsPy() try: output = invoker.RunAs(username, password, cmd, domainName, processTimeout, logonType, createProcessFunction, remote, forceUserProfileCreation, bypassUac, remoteImpersonation) except Exception as e: invoker.CleanupHandles() output = f"{e}" return output
47,817
Python
.py
750
53.461333
419
0.702017
rkbennett/RunAsPy
8
1
0
AGPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,795
get_outline.py
Kick-H_NEP-water/compare_MB-pol_SCAN/Related_Programs/get_outline.py
""" Purpose: Get the points with the largest errors in the force_train.out, virial_train.out or energy_train.out file, and find the ID of the training set to which these points belong and output it. Now, added function to selectively output remaining structures. Notice: the number of output trajectories is less than or equal to the number of error points Run: python get_max_rmse_xyz.py train.xyz force_train.out 13 python get_max_rmse_xyz.py train.xyz virial_train.out 13 python get_max_rmse_xyz.py train.xyz energy_train.out 13 """ import numpy as np import sys def Get_rmse_ids(nmax, file_force_loss): frmse = np.loadtxt(file_force_loss) if frmse.shape[1] == 6: rmse = np.sum(np.abs(frmse[:,0:2]-frmse[:,3:5]), axis=1) file_type = "force" elif frmse.shape[1] == 12: rmse = np.sum(np.abs(frmse[:,0:5]-frmse[:,6:11]), axis=1) file_type = "virial" elif frmse.shape[1] == 2: rmse = np.abs(frmse[:,0]-frmse[:,1]) file_type = "energy" else: raise "Error in outfiles." rmse_max_ids = np.argsort(-rmse) return rmse[rmse_max_ids[:nmax]], rmse_max_ids[:nmax], file_type def Get_fram_line(train_xyz): num_lines, num_atoms = [], [] with open(train_xyz, "r") as fi: flines = fi.readlines() for i, line in enumerate(flines): if "energy" in line or "Energy" in line: num_lines.append(i-1) num_atoms.append(int(flines[i-1])) return num_lines, num_atoms def Print_MAX_xyz(nf_mark, num_lines, train_xyz, fout="find_out.xyz", fres=None): fout_str = "" if fres != None: fout_not = "" with open(train_xyz, "r") as fi: flines = fi.readlines() for fi in range(len(nf_mark)): flsta = num_lines[fi] if fi == len(num_lines): flend = len(flines) else: try: flend = num_lines[fi+1] except: flend = len(train_xyz) if nf_mark[fi]: fout_str += "".join(flines[flsta:flend]) else: if fres != None: fout_not += "".join(flines[flsta:flend]) fo = open(fout, 'w') fo.write(fout_str) fo.close() if fres != None: fr = open(fres, 'w') fr.write(fout_not) fr.close() fxyz = sys.argv[1] floss = sys.argv[2] nmax = int(sys.argv[3]) fname = sys.argv[4] rmse_max, rmse_ids, file_type = Get_rmse_ids(nmax, floss) num_lines, num_atoms = Get_fram_line(fxyz) sum_atoms = np.cumsum(num_atoms) nf_mark = np.zeros((len(num_lines))) for i in rmse_ids: if file_type == "force": nfram = np.searchsorted(sum_atoms, i) else: nfram = i nf_mark[nfram] = 1 #print(f"The lagerest RMSE with {nmax} atom are located in fram {sel_flist}") Print_MAX_xyz(nf_mark, num_lines, fxyz, fout=f'findout-{fname}.xyz', fres=f'reserve-{fname}.xyz')
3,039
Python
.py
83
28.843373
97
0.586113
Kick-H/NEP-water
8
0
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,796
nep_fps_select_all.py
Kick-H_NEP-water/compare_MB-pol_SCAN/Related_Programs/nep_fps_select_all.py
from pynep.calculate import NEP from pynep.select import FarthestPointSample from ase.io import read, write import numpy as np import matplotlib.pyplot as plt from sklearn.decomposition import PCA from multiprocessing import Pool import sys def map_fun(frame): return np.mean(calc.get_property('descriptor', frame), axis=0) if __name__=='__main__': nep_dir = "" nep_dir = "." proc_n=int(sys.argv[1]) in_xyz = nep_dir+"/"+sys.argv[2] in_nep = nep_dir+"/nep.txt" min_des = float(sys.argv[3]) minsel = int(sys.argv[4]) runame=sys.argv[5] data_current=read(in_xyz,index=':',format='extxyz') calc = NEP(in_nep) # print(calc) # select data with Pool(processes=proc_n) as pool: des_current=np.array(pool.map(map_fun,data_current)) sampler = FarthestPointSample(min_distance=min_des) selected_i = sampler.select(des_current, [], min_select=minsel) write(f'selected-{runame}.xyz', [data_current[i] for i in selected_i],format='extxyz') np.savetxt(f"selected-{runame}",selected_i) # fit PCA model reducer = PCA(n_components=2) reducer.fit(des_current) # current data proj_current = reducer.transform(des_current) plt.scatter(proj_current[:,0], proj_current[:,1],label=f"init-{runame}",color="orange") # selected data proj_selected = reducer.transform(np.array([des_current[i] for i in selected_i])) plt.scatter(proj_selected[:,0], proj_selected[:,1],s=1,label="selected",color='blue') plt.legend() plt.axis('off') plt.savefig(f'select-{runame}.png')
1,576
Python
.py
41
34.146341
91
0.687827
Kick-H/NEP-water
8
0
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,797
plot_nep_water.py
Kick-H_NEP-water/compare_MB-pol_SCAN/Related_Programs/plot_nep_water.py
import numpy as np from pylab import * import sys ##set figure properties aw = 1.5 fs = 16 lw = 2.0 font = {'size' : fs} matplotlib.rc('font', **font) matplotlib.rc('axes' , lw=aw) def set_fig_properties(ax_list): tl = 6 tw = 1.5 tlm = 3 for ax in ax_list: ax.tick_params(which='major', length=tl, width=tw) ax.tick_params(which='minor', length=tlm, width=tw) ax.tick_params(which='both', axis='both', direction='out', right=False, top=False) def plot_nep(pout): nep = np.loadtxt("./nep.txt", skiprows=6) figure(figsize=(16, 7)) subplot(1,2,1) hist(np.log(np.abs(nep)), bins=50) subplot(1,2,2) scatter(range(len(nep)), nep, s=0.5) gcf().set_size_inches(9,3) savefig(pout, dpi=300) def plot_loss(loss, test=True): loss_title = "gen total l1 l2 e_train f_train v_train e_test f_test v_test".split(' ') loss[:,0] = np.arange(1, len(loss)+1) for i in range(1, 7): loglog(loss[:, 0], loss[:, i], ls="-", lw=lw, label=loss_title[i]) if test: for i in range(7, 10): loglog(loss[:, 0], loss[:, i], ls="-", lw=lw, label=loss_title[i]) xlabel('Generation/100') ylabel('Loss') legend(loc="lower left", ncol=2, fontsize=14, frameon=False, columnspacing=0.2) # tight_layout() def find_units(name): if name == "force": return ['eV/A/atom', 'meV/A/atom', 4] elif name == "energy": return ['eV/atom', 'meV/atom', 3] elif name == "virial": return ['eV/atom', 'meV/atom', 5] elif name == "stress": return ['GPa', 'MPa', 5] def plot_nep_dft(data, title): # title = [name, type, units] # example: title = ['force', 'eV/A/atom', 'train'] nclo = int(data.shape[1]/2) targe = data[:, :nclo].reshape(-1) predi = data[:, nclo:].reshape(-1) pids = np.abs(targe - predi) < 10 if np.sum(pids) != len(targe): print(f"WARNING: There are {len(targe)-np.sum(pids)} frams mismatch in {title[0]} {title[1]}") targe = targe[pids] predi = predi[pids] units = find_units(title[0]) data_min = np.min([np.min(targe),np.min(predi)]) data_max = np.max([np.max(targe),np.max(predi)]) data_min -= (data_max-data_min)*0.1 data_max += (data_max-data_min)*0.1 plot([data_min, data_max], [data_min, data_max], c="grey", lw=3) xlim([data_min, data_max]) ylim([data_min, data_max]) RMSE = np.sqrt(((predi - targe) ** 2).mean()) color = f"C{units[2]}" if title[1] == 'test': color = f"C{units[2]+3}" plot(targe, predi, '.', color=color) xlabel(f'DFT {title[0]} ({units[0]})') ylabel(f'NEP {title[0]} ({units[0]})') legend([f'{title[1]} RMSE:{1000*RMSE:.4f} {units[1]}'], loc="upper left") if print_rmse: print(" >>", title[0], title[1], f'{1000*RMSE:.4f}', units[1]) # tight_layout() def plot_nep_nep(data_train, data_test, title): # title = [name, type, units] # example: title = ['force', 'eV/A/atom', 'train'] nclo = int(data_train.shape[1]/2) train = data_train[:, nclo:].reshape(-1) test = data_test[:, nclo:].reshape(-1) train = np.select([np.logical_and(train>-1e5, train<1e5)], [train]) test = np.select([np.logical_and(test>-1e5, test<1e5)], [test]) units = find_units(title[0]) data_min = np.min([np.min(train),np.min(test)]) data_max = np.max([np.max(train),np.max(test)]) data_min -= (data_max-data_min)*0.1 data_max += (data_max-data_min)*0.1 plot([data_min, data_max], [data_min, data_max], c="grey", lw=3) xlim([data_min, data_max]) ylim([data_min, data_max]) RMSE = np.sqrt(((test - train) ** 2).mean()) color = f"C{units[2]}" if title[1] == 'test': color = f"C{units[2]+3}" plot(train, test, '.', color=color) xlabel(f'Train {title[0]} ({units[0]})') ylabel(f'Test {title[0]} ({units[0]})') legend([f'{title[1]} RMSE:{1000*RMSE:.4f} {units[1]}'], loc="upper left") # tight_layout() def plot_out(plot_model, out_name="nep_out.png"): nep_out_files = ['loss.out', 'energy_train.out', 'energy_test.out', 'force_train.out', 'force_test.out'] try: open('stress_train.out', 'r') nep_out_files += ['stress_train.out', 'stress_test.out'] stress_flag = 1 except FileNotFoundError: nep_out_files += ['virial_train.out', 'virial_test.out'] print('WARNING: There is no stress file, use the virial file.') stress_flag = 0 except: print('WARNING: There is no virial and stress files.') stress_flag = -1 data_list = {} for file in nep_out_files: try: data_list[file] = np.loadtxt(file) except: data_list[file] = None if plot_model == 0: plot_data = [1, 1, 0, 1, 0, 1, 0] elif plot_model == 1: plot_data = [1, 0, 1, 0, 1, 0, 1] elif plot_model == 2: plot_data = [1, 1, 1, 1, 1, 1, 1] elif plot_model == 3: plot_data = [0, 1, 0, 1, 0, 1, 0] elif plot_model == 4: plot_data = [0, 0, 1, 0, 1, 0, 1] elif plot_model == 5: plot_data = [0, 1, 1, 1, 1, 1, 1] plot_sum = np.sum(plot_data) if plot_sum in [4, 7]: # plot train_test with loss. figure(figsize=(16, 14)) subplot(2,2,1) set_fig_properties([gca()]) # plot_loss plot_loss(data_list[nep_out_files[0]], test=plot_data[2]) for i in range(3): # plot_train_test subplot(2,2,i+2) set_fig_properties([gca()]) file_train_ids = 1+2*i if plot_data[file_train_ids] == 1: # plot_train file_name = nep_out_files[file_train_ids] title = file_name.split('.')[0].split('_') plot_nep_dft(data_list[file_name], title) file_test_ids = 2+2*i if plot_data[file_test_ids] == 1: # plot_test file_name = nep_out_files[file_test_ids] title = file_name.split('.')[0].split('_') plot_nep_dft(data_list[file_name], title) elif plot_sum in [3]: figure(figsize=(24, 7)) for i in range(3): subplot(1,3,i+1) file_train_ids = 1+2*i if plot_data[file_train_ids] == 1: file_name = nep_out_files[file_train_ids] title = file_name.split('.')[0].split('_') plot_nep_dft(data_list[file_name], title) file_test_ids = 2+2*i if plot_data[file_test_ids] == 1: file_name = nep_out_files[file_test_ids] title = file_name.split('.')[0].split('_') plot_nep_dft(data_list[file_name], title) elif plot_sum in [6]: figure(figsize=(24, 7)) for i in range(3): subplot(1,3,i+1) file_train_ids = 1+2*i file_test_ids = 2+2*i if plot_data[file_train_ids] == 1 and plot_data[file_test_ids] == 1: file_train_name = nep_out_files[file_train_ids] file_test_name = nep_out_files[file_test_ids] title = file_train_name.split('.')[0].split('_') plot_nep_nep(data_list[file_train_name], data_list[file_test_name], title) savefig(out_name, dpi=150, bbox_inches='tight') # plot_model = 0 # 0, train: loss+train # plot_model = 1 # 1, test: loss+test # plot_model = 2 # 2, train+test: loss+train+test # plot_model = 3 # 3, predict: train # plot_model = 4 # 4, predict: test # plot_model = 5 # 5, compare: train_nep:test_nep name_list = ["nep_train.png", "nep_test.png", "nep_train_test.png", "train.png", "test.png", "compare.png"] plot_model = int(sys.argv[1]) print_rmse = True plot_out(plot_model, out_name=name_list[plot_model]) if plot_model in [0, 1, 2]: plot_nep("nep_txt.png")
7,790
Python
.py
182
35.450549
107
0.564333
Kick-H/NEP-water
8
0
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,798
SS_OCR.py
op200_Simple_Subtitle_OCR/SS_OCR.py
import tkinter as tk from tkinter import ttk import cv2 from PIL import Image, ImageTk import numpy as np from math import floor from threading import Thread from time import sleep import os os.environ['KMP_DUPLICATE_LIB_OK']='True' import webbrowser def hyperlink_jump(hyperlink:str): webbrowser.open(hyperlink) import shutil PROGRAM_NAME = "Simple Subtitle OCR" VERSION = "0.7" HOME_LINK = "https://github.com/op200/Simple_Subtitle_OCR" #日志 class log: @staticmethod def output(info:str): log_Text.insert(tk.END,info+'\n') log_Text.see(tk.END) print(info) @staticmethod def error(info:str): log.output(f"[ERROR] {info}") @staticmethod def warning(info:str): log.output(f"[WARNING] {info}") @staticmethod def info(info:str): log.output(f"[INFO] {info}") import platform #判断系统对应路径 os_type = platform.system() if os_type == 'Windows': config_dir = os.path.join(os.getenv('APPDATA'), 'SS_OCR') elif os_type == 'Linux' or os_type == 'Darwin': config_dir = os.path.join(os.path.expanduser('~'), '.config', 'SS_OCR') else: config_dir = "" log.warning("无法确认系统") os.makedirs(config_dir, exist_ok=True) ocr_choice:int = 1 import configparser #不存在配置则写入默认配置 config = configparser.ConfigParser() config_file_pathname = os.path.join(config_dir, 'config.ini') if not os.path.exists(config_file_pathname) or config.read(config_file_pathname) and config.get("DEFAULT","version")!=VERSION: config["DEFAULT"] = { "version" : VERSION, "ocr" : "PaddleOCR", "language" : "ch", "srt_path" : r".\output.srt", "srt_overwrite" : 0, "use_gpu" : 0, "set_filter" : 0, "retain_color_tolerance" : 40, "retain_color1" : "#ffffff", "retain_color2" : "#000000" } with open(config_file_pathname, 'w') as configfile: config.write(configfile) def save_config(): config["DEFAULT"]["language"] = set_language_Entry.get() config["DEFAULT"]["srt_path"] = set_srtPath_Entry.get() config["DEFAULT"]["srt_overwrite"] = "1" if srt_overwrite_Tkbool.get() else "0" config["DEFAULT"]["use_gpu"] = "1" if open_gpu_Tkbool.get() else "0" config["DEFAULT"]["set_filter"] = "1" if set_filter_Tkbool.get() else "0" config["DEFAULT"]["retain_color_tolerance"] = str(retain_color_tolerance_Tkint.get()) config["DEFAULT"]["retain_color1"] = retain_color1_Entry.get() config["DEFAULT"]["retain_color2"] = retain_color2_Entry.get() try: with open(config_file_pathname, 'w') as configfile: config.write(configfile) except FileNotFoundError: pass path:str scale, frame_height, frame_width, new_frame_height, new_frame_width = False, int,int,int,int right_x,right_y,left_x,left_y = 0,0,0,0 fps:int difference_list:list VIDEO_FRAME_IMG_HEIGHT = 6 root_Tk = tk.Tk() root_Tk.title(PROGRAM_NAME) def root_Tk_Close(): save_config() root_Tk.destroy() root_Tk.protocol("WM_DELETE_WINDOW", root_Tk_Close) #样式 from tkinter import font as tkfont TkDefaultFont = tkfont.nametofont("TkDefaultFont").actual()['family'] underline_font = tkfont.Font(family=TkDefaultFont, size=tkfont.nametofont("TkDefaultFont").actual()['size'], underline=True) #菜单 menu_Menu = tk.Menu(root_Tk) menu_setting_Menu = tk.Menu(menu_Menu, tearoff=0) menu_setting_switchOCR_Menu = tk.Menu(menu_Menu, tearoff=0) def switch_to_paddleocr(): global config,ocr_choice if os.path.exists(config_file_pathname): config["DEFAULT"]["ocr"]="PaddleOCR" config["DEFAULT"]["language"]="ch" with open(config_file_pathname, 'w') as configfile: config.write(configfile) ocr_choice = 1 set_language_Entry.delete(0,tk.END) set_language_Entry.insert(0,"ch") log.info("切换至PaddleOCR") def switch_to_EasyOCR(): global config,ocr_choice if os.path.exists(config_file_pathname): config["DEFAULT"]["ocr"]="EasyOCR" config["DEFAULT"]["language"]="ch_sim,en" with open(config_file_pathname, 'w') as configfile: config.write(configfile) ocr_choice = 2 set_language_Entry.delete(0,tk.END) set_language_Entry.insert(0,"ch_sim,en") log.info("切换至EasyOCR") menu_setting_switchOCR_Menu.add_command(label="PaddleOCR",command=switch_to_paddleocr) menu_setting_switchOCR_Menu.add_command(label="EasyOCR",command=switch_to_EasyOCR) menu_Menu.add_cascade(label="设置",menu=menu_setting_Menu) menu_setting_Menu.add_cascade(label="切换OCR库",menu=menu_setting_switchOCR_Menu) def remove_config_dir(): if os.path.exists(config_dir): shutil.rmtree(config_dir) log.info("已删除"+config_dir) else: log.error("未找到配置文件目录"+config_dir) menu_setting_Menu.add_command(label="清除配置文件",command=remove_config_dir) def create_help_about_Toplevel(): about_Toplevel = tk.Toplevel(root_Tk,width=20,height=15) about_Toplevel.geometry('320x160') about_Toplevel.title("About") frame = ttk.Frame(about_Toplevel) frame.pack(expand=True) ttk.Label(frame,text=f"{PROGRAM_NAME} v{VERSION}\n\n").pack() hyperlink_Label = ttk.Label(frame,text=HOME_LINK, cursor="hand2", foreground="blue", font=underline_font) hyperlink_Label.bind("<Button-1>",lambda _:hyperlink_jump(HOME_LINK)) hyperlink_Label.pack() menu_help_Menu = tk.Menu(menu_Menu, tearoff=0) menu_help_Menu.add_command(label="关于",command=create_help_about_Toplevel) menu_Menu.add_cascade(label="帮助",menu=menu_help_Menu) root_Tk.config(menu=menu_Menu) #左侧控件 left_Frame = ttk.Frame(root_Tk, cursor="tcross") left_Frame.grid(row=0,column=0,padx=5,pady=5) #右侧控件 right_Frame = ttk.Frame(root_Tk) right_Frame.grid(row=0,column=1,padx=5,pady=5) #左侧控件 #视频预览控件 video_review_Label = ttk.Label(left_Frame, cursor="target") #进度条控件 video_Progressbar = ttk.Progressbar(left_Frame) def draw_video_frame_Label_frameColor(frame_num:int, color:tuple[int,int,int]): global video_frame_img x = round(new_frame_width*frame_num/(frame_count-1))-1 if x<0: x=0 video_frame_img[:VIDEO_FRAME_IMG_HEIGHT-1, x] = color def flush_video_frame_Label(): photo = ImageTk.PhotoImage(Image.fromarray(video_frame_img)) video_frame_Label.config(image=photo) video_frame_Label.image = photo def draw_video_frame_Label_range(start_frame:int, end_frame:int, color:tuple[int,int,int]): global video_frame_img video_frame_img[-1,:,:]=0 video_frame_img[-1, max(round(new_frame_width*start_frame/(frame_count-1))-1, 0):max(round(new_frame_width*end_frame/(frame_count-1))-1, 0) + 1] = color video_frame_Label = ttk.Label(left_Frame) frame_count = 0 frame_now = 0 def img_filter(frame:cv2.typing.MatLike): tolerance = retain_color_tolerance_Tkint.get() color1 = tuple(int(retain_color1_Entry.get().lstrip('#')[i:i+2], 16) for i in (0, 2, 4)) color2 = tuple(int(retain_color2_Entry.get().lstrip('#')[i:i+2], 16) for i in (0, 2, 4)) # 定义颜色上下界 lower1 = np.array([max(0, (color1[0] - tolerance)), max(0, (color1[1] - tolerance)), max(0, (color1[2] - tolerance))]) upper1 = np.array([min(255, (color1[0] + tolerance)), min(255, (color1[1] + tolerance)), min(255, (color1[2] + tolerance))]) lower2 = np.array([max(0, (color2[0] - tolerance)), max(0, (color2[1] - tolerance)), max(0, (color2[2] - tolerance))]) upper2 = np.array([min(255, (color2[0] + tolerance)), min(255, (color2[1] + tolerance)), min(255, (color2[2] + tolerance))]) # 创建掩码 mask1 = cv2.inRange(frame, lower1, upper1) mask2 = cv2.inRange(frame, lower2, upper2) # 合并掩码 mask = cv2.bitwise_or(mask1, mask2) mask = cv2.bitwise_not(mask) purple = (142, 12, 255) frame[mask > 0] = purple return frame #跳转当前帧 def jump_to_frame(): global scale,frame_now,frame_count main_rendering_Cap.set(cv2.CAP_PROP_POS_FRAMES,frame_now) frame = main_rendering_Cap.read()[1] try: frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) except cv2.error: log.warning(f"[{frame_now}]该帧无法读取(应检查视频封装)") else: if set_filter_Tkbool.get(): frame = img_filter(frame) #重新绘制选框 if scale: frame = cv2.resize(frame,(new_frame_width,new_frame_height)) cv2.rectangle(frame,(right_x, right_y, left_x-right_x, left_y-right_y), color=(0,255,255),thickness=1) video_Progressbar["value"] = frame_now/(frame_count-1)*100 photo = ImageTk.PhotoImage(Image.fromarray(frame)) video_review_Label.config(image=photo) video_review_Label.image = photo #set frame_now frame_now_Tkint.set(frame_now) #进度条的滚轮事件 def video_progressbar_mousewheel(event): global frame_now,frame_count frame_now += (1 if event.delta<0 else -1) if frame_now<0: frame_now=0 if frame_now>=frame_count: frame_now=frame_count-1 jump_to_frame() video_review_Label.bind("<MouseWheel>", video_progressbar_mousewheel) video_Progressbar.bind("<MouseWheel>", video_progressbar_mousewheel) video_frame_Label.bind("<MouseWheel>", video_progressbar_mousewheel) #进度条鼠标点击事件 def video_progressbar_leftDrag(event): ratio = event.x / video_Progressbar.winfo_width() if ratio>1: ratio=1 if ratio<0: ratio=0 # video_Progressbar["value"] = ratio*100 global frame_now,frame_count frame_now = int((frame_count-1)*ratio) jump_to_frame() video_Progressbar.bind("<B1-Motion>", video_progressbar_leftDrag) video_Progressbar.bind("<Button-1>", video_progressbar_leftDrag) video_frame_Label.bind("<B1-Motion>", video_progressbar_leftDrag) video_frame_Label.bind("<Button-1>", video_progressbar_leftDrag) #输入路径 初始化 def submit_path(_): log.info("使用的OCR库是: "+config.get("DEFAULT","ocr")) global path,scale,main_rendering_Cap,sec_rendering_Cap,frame_count,frame_height,frame_width,new_frame_height,new_frame_width,fps,difference_list,frame_now path = input_video_Entry.get() #渲染控件 frame_num_Frame.grid(row=2,column=0) draw_box_Frame.grid(row=4,column=0,pady=15) set_filter_Frame.grid(row=6,column=0) ocr_set_Frame.grid(row=7,column=0,pady=15) set_srt_Frame.grid(row=0,column=0,pady=10) set_ocr_Frame.grid(row=1,column=0,pady=10) log_Frame.grid(row=8,column=0,pady=10) sec_rendering_Cap = cv2.VideoCapture(path) main_rendering_Cap = cv2.VideoCapture(path) main_rendering_Cap.set(cv2.CAP_PROP_POS_FRAMES,0) ret, frame = main_rendering_Cap.read() if ret: #获取尺寸 判断缩放 frame_height, frame_width, _ = frame.shape video_size_Label.config(text=str(frame_width)+" x "+str(frame_height)) fps = main_rendering_Cap.get(cv2.CAP_PROP_FPS) video_fps_Label.config(text=str(fps)+" FPS") video_size_Label.grid(row=0,column=0) video_fps_Label.grid(row=0,column=1,padx=8) if frame_height > root_Tk.winfo_screenheight()*5/6 or frame_width > root_Tk.winfo_screenwidth()*4/5: scale = max((1.2*frame_height+100)/root_Tk.winfo_screenheight(), (1.2*frame_width+500)/root_Tk.winfo_screenwidth(), 1.5) new_frame_width,new_frame_height = int(frame_width/scale),int(frame_height/scale) frame = cv2.resize(frame,(new_frame_width,new_frame_height)) log.info(f"视频画幅过大 预览画面已缩小(1/{scale:.2f}-->{new_frame_width}x{new_frame_height})") else: new_frame_width,new_frame_height = frame_width,frame_height scale = False #重写进度条 video_review_Label.grid(row=0,column=0,pady=5) video_Progressbar.config(length=new_frame_width) video_Progressbar.grid(row=2,column=0) #渲染进度 frame_now = 0 jump_to_frame() #初始化右侧控件 frame_count = int(main_rendering_Cap.get(cv2.CAP_PROP_FRAME_COUNT)) difference_list = [-1]*frame_count#初始化差值表 frame_count_Label.config(text = f" / {frame_count-1:9d}") frame_now_Tkint.set(0) video_path_review_text = input_video_Entry.get() if len(video_path_review_text)>49: video_path_review_text = video_path_review_text[0:49]+"\n"+video_path_review_text[49:] if len(video_path_review_text)>99: video_path_review_text = video_path_review_text[0:99]+"\n"+video_path_review_text[99:] if len(video_path_review_text)>149: video_path_review_text = video_path_review_text[0:149]+"\n"+video_path_review_text[149:] video_path_review_Label.config(text=video_path_review_text) #绘制进度条的帧提示 global video_frame_img video_frame_img = np.ones((VIDEO_FRAME_IMG_HEIGHT,new_frame_width,3), np.uint8) * 224 video_frame_img[-1,:,:] = 1 for frame_num in range(0,frame_count): draw_video_frame_Label_frameColor(frame_num, (0,0,0)) flush_video_frame_Label() video_frame_Label.grid(row=3,column=0) else: log.error("无法打开"+path) root_Tk.focus_set() #右侧控件 #路径输入 input_video_Frame = ttk.Frame(right_Frame) input_video_Frame.grid(row=1,column=0,pady=15) video_path_review_Label = ttk.Label(input_video_Frame,text="输入视频路径名") video_path_review_Label.grid(row=1,column=0,columnspan=2,pady=8) input_video_Entry = ttk.Entry(input_video_Frame,width=40) input_video_Entry.grid(row=2,column=0) input_video_Entry.focus_set() input_video_Entry.bind("<Return>", submit_path) input_video_Button = ttk.Button(input_video_Frame, text="提交", width=4, command=lambda:submit_path(None)) input_video_Button.grid(row=2,column=1,padx=5) #帧数 frame_num_Frame = ttk.Frame(right_Frame) def enter_to_change_frame_now(_): global frame_now,frame_count frame_now = int(frame_now_Entry.get()) if frame_now<0: frame_now=0 if frame_now>=frame_count: frame_now=frame_count-1 jump_to_frame() root_Tk.focus_set() frame_now_Frame = ttk.Frame(frame_num_Frame) frame_now_Frame.grid(row=0,column=0) frame_now_Tkint = tk.IntVar() frame_now_Entry = ttk.Entry(frame_now_Frame,textvariable=frame_now_Tkint,width=5) frame_now_Entry.bind("<Return>", enter_to_change_frame_now) frame_now_Entry.grid(row=0,column=0) frame_count_Label = ttk.Label(frame_now_Frame,text=" / NULL") frame_count_Label.grid(row=0,column=1) #帧数区间 frame_range_Frame = ttk.Frame(frame_num_Frame) frame_range_Frame.grid(row=1,column=0) def set_start_frame_num_Click(frame1_Tkint:tk.IntVar, frame2_Tkint:tk.IntVar, flush_frame_now:int=None): if flush_frame_now: global frame_now frame_now = flush_frame_now jump_to_frame() frame1_Tkint.set(frame_now_Tkint.get()) if start_frame_num_Tkint.get() > end_frame_num_Tkint.get(): frame2_Tkint.set(frame1_Tkint.get()) draw_video_frame_Label_range(start_frame_num_Tkint.get(),end_frame_num_Tkint.get(),(228,12,109)) flush_video_frame_Label() start_frame_num_Tkint = tk.IntVar() start_frame_num_Entry = ttk.Entry(frame_range_Frame,width=11,textvariable=start_frame_num_Tkint) start_frame_num_Entry.bind("<Return>", lambda _:set_start_frame_num_Click(start_frame_num_Tkint,end_frame_num_Tkint,start_frame_num_Tkint.get())) set_start_frame_num_Button = ttk.Button(frame_range_Frame,text="设为开始帧",command=lambda:set_start_frame_num_Click(start_frame_num_Tkint,end_frame_num_Tkint)) start_frame_num_Entry.grid(row=0,column=0,padx=14,pady=5) set_start_frame_num_Button.grid(row=1,column=0) end_frame_num_Tkint = tk.IntVar() end_frame_num_Entry = ttk.Entry(frame_range_Frame,width=11,textvariable=end_frame_num_Tkint) end_frame_num_Entry.bind("<Return>", lambda _:set_start_frame_num_Click(end_frame_num_Tkint,start_frame_num_Tkint,end_frame_num_Tkint.get())) set_end_frame_num_Button = ttk.Button(frame_range_Frame,text="设为结束帧",command=lambda:set_start_frame_num_Click(end_frame_num_Tkint,start_frame_num_Tkint)) end_frame_num_Entry.grid(row=0,column=1,padx=14) set_end_frame_num_Button.grid(row=1,column=1) #视频信息 video_info_Frame = ttk.Frame(right_Frame) video_info_Frame.grid(row=3,column=0,pady=10) video_size_Label = ttk.Label(video_info_Frame) video_fps_Label = ttk.Label(video_info_Frame) #选框位置 draw_box_Frame = ttk.Frame(right_Frame) left_x_text,left_y_text,right_x_text,right_y_text = tk.IntVar(),tk.IntVar(),tk.IntVar(),tk.IntVar() draw_box_left_x,draw_box_left_y = ttk.Entry(draw_box_Frame,textvariable=left_x_text,width=5),ttk.Entry(draw_box_Frame,textvariable=left_y_text,width=5) draw_box_right_x,draw_box_right_y = ttk.Entry(draw_box_Frame,textvariable=right_x_text,width=5),ttk.Entry(draw_box_Frame,textvariable=right_y_text,width=5) draw_box_left_x.grid(row=0,column=0,padx=15) draw_box_left_y.grid(row=0,column=1,padx=15) draw_box_right_x.grid(row=0,column=2,padx=15) draw_box_right_y.grid(row=0,column=3,padx=15) def enter_to_change_draw_box(_): global scale,right_x,right_y,left_x,left_y,difference_list difference_list = [-1]*frame_count if left_x_text.get() < 0: left_x_text.set(0) if left_y_text.get() < 0: left_y_text.set(0) if right_x_text.get() >= frame_width: right_x_text.set(frame_width) if right_y_text.get() >= frame_height: right_y_text.set(frame_height) if scale: right_x = int(left_x_text.get()*new_frame_width/frame_width) right_y = int(left_y_text.get()*new_frame_width/frame_width) left_x = int(right_x_text.get()*new_frame_width/frame_width) left_y = int(right_y_text.get()*new_frame_width/frame_width) else: right_x = left_x_text.get() right_y = left_y_text.get() left_x = right_x_text.get() left_y = right_y_text.get() main_rendering_Cap.set(cv2.CAP_PROP_POS_FRAMES,frame_now) _, frame = main_rendering_Cap.read() frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if scale: frame = cv2.resize(frame,(new_frame_width,new_frame_height)) cv2.rectangle(frame,(right_x, right_y, left_x-right_x, left_y-right_y), color=(0,255,255),thickness=1) photo = ImageTk.PhotoImage(Image.fromarray(frame)) video_review_Label.config(image=photo) video_review_Label.image = photo root_Tk.focus_set() draw_box_left_x.bind("<Return>", enter_to_change_draw_box) draw_box_left_y.bind("<Return>", enter_to_change_draw_box) draw_box_right_x.bind("<Return>", enter_to_change_draw_box) draw_box_right_y.bind("<Return>", enter_to_change_draw_box) #输出相关控件 output_setup_Frame = ttk.Frame(right_Frame) output_setup_Frame.grid(row=5,column=0) set_srt_Frame = ttk.Frame(output_setup_Frame) set_srtPath_Label = ttk.Label(set_srt_Frame,text="SRT位置:") set_srtPath_Label.grid(row=0,column=0) set_srtPath_Entry = ttk.Entry(set_srt_Frame) set_srtPath_Entry.insert(0,config.get("DEFAULT","srt_path")) set_srtPath_Entry.grid(row=0,column=1) srt_overwrite_Tkbool = tk.BooleanVar() srt_overwrite_Tkbool.set(bool(int(config.get("DEFAULT","srt_overwrite")))) srt_overwrite_set = ttk.Checkbutton(set_srt_Frame,text="覆写SRT",var=srt_overwrite_Tkbool) srt_overwrite_set.grid(row=0,column=2,padx=10) set_ocr_Frame = ttk.Frame(output_setup_Frame) set_language_title_Label = ttk.Label(set_ocr_Frame,text="OCR语言:") set_language_title_Label.grid(row=0,column=1) set_language_Entry = ttk.Entry(set_ocr_Frame) set_language_Entry.insert(0,config.get("DEFAULT","language")) set_language_Entry.grid(row=0,column=2) open_gpu_Tkbool = tk.BooleanVar() open_gpu_Tkbool.set(bool(int(config.get("DEFAULT","use_gpu")))) open_gpu_set_Checkbutton = ttk.Checkbutton(set_ocr_Frame,text="使用GPU",var=open_gpu_Tkbool) open_gpu_set_Checkbutton.grid(row=0,column=3,padx=10) #filter相关控件 set_filter_Frame = ttk.Frame(right_Frame) set_filter_Tkbool = tk.BooleanVar() set_filter_Tkbool.set(bool(int(config.get("DEFAULT","set_filter")))) def set_filter_set_event(): if set_filter_Tkbool.get(): retain_color_tolerance_Entry.config(state=tk.NORMAL) retain_color1_Entry.config(state=tk.NORMAL) retain_color2_Entry.config(state=tk.NORMAL) else: retain_color_tolerance_Entry.config(state=tk.DISABLED) retain_color1_Entry.config(state=tk.DISABLED) retain_color2_Entry.config(state=tk.DISABLED) jump_to_frame() set_filter_set = ttk.Checkbutton(set_filter_Frame,text="启用滤镜",var=set_filter_Tkbool,command=set_filter_set_event) set_filter_set.grid(row=0,column=0) retain_color_tolerance_Frame = ttk.Frame(set_filter_Frame) retain_color_tolerance_Frame.grid(row=0,column=1,padx=5) retain_color_tolerance_Label = ttk.Label(retain_color_tolerance_Frame,text="容差") retain_color_tolerance_Label.grid(row=0,column=0) retain_color_tolerance_Tkint = tk.IntVar(value=int(config.get("DEFAULT","retain_color_tolerance"))) retain_color_tolerance_Entry = ttk.Entry(retain_color_tolerance_Frame,textvariable=retain_color_tolerance_Tkint,width=4) retain_color_tolerance_Entry.grid(row=0,column=1) retain_color_tolerance_Entry.bind("<Return>", lambda _:jump_to_frame()) set_color_Frame = ttk.Frame(set_filter_Frame) set_color_Frame.grid(row=0,column=2) retain_color1_preview_Canvas = tk.Canvas(set_color_Frame, width=10, height=10, borderwidth=0, highlightthickness=1, highlightbackground='gray') retain_color1_preview_Canvas.grid(row=0,column=0,padx=5) retain_color1_Entry = ttk.Entry(set_color_Frame,width=8) retain_color1_Entry.insert(0,config.get("DEFAULT","retain_color1")) retain_color1_Entry.grid(row=0,column=1) retain_color2_preview_Canvas = tk.Canvas(set_color_Frame, width=10, height=10, borderwidth=0, highlightthickness=1, highlightbackground='gray') retain_color2_preview_Canvas.grid(row=0,column=2,padx=5) retain_color2_Entry = ttk.Entry(set_color_Frame,width=8) retain_color2_Entry.insert(0,config.get("DEFAULT","retain_color2")) retain_color2_Entry.grid(row=0,column=3) if set_filter_Tkbool.get(): retain_color_tolerance_Entry.config(state=tk.NORMAL) retain_color1_Entry.config(state=tk.NORMAL) retain_color2_Entry.config(state=tk.NORMAL) else: retain_color_tolerance_Entry.config(state=tk.DISABLED) retain_color1_Entry.config(state=tk.DISABLED) retain_color2_Entry.config(state=tk.DISABLED) def enter_to_draw_retain_color(_): try: retain_color1_preview_Canvas.create_rectangle(-40, -40, 40, 40, fill=retain_color1_Entry.get()) retain_color2_preview_Canvas.create_rectangle(-40, -40, 40, 40, fill=retain_color2_Entry.get()) except: log.error("颜色格式错误") jump_to_frame() retain_color1_Entry.bind("<Return>", enter_to_draw_retain_color) retain_color2_Entry.bind("<Return>", enter_to_draw_retain_color) try: retain_color1_preview_Canvas.create_rectangle(-40, -40, 40, 40, fill=retain_color1_Entry.get()) retain_color2_preview_Canvas.create_rectangle(-40, -40, 40, 40, fill=retain_color2_Entry.get()) except: log.error("颜色格式错误") ocr_set_Frame = ttk.Frame(right_Frame) threshold_value_input_Frame = ttk.Frame(ocr_set_Frame) threshold_value_input_Frame.grid(row=0,column=0) threshold_value_input_title_Label = ttk.Label(threshold_value_input_Frame,text="转场检测阈值:") threshold_value_input_title_Label.grid(row=0,column=0) threshold_value_input_Tkint = tk.IntVar(value=-1) threshold_value_input_Entry = ttk.Entry(threshold_value_input_Frame,width=5,textvariable=threshold_value_input_Tkint) threshold_value_input_Entry.grid(row=0,column=1) start_threshold_detection_Frame = tk.Frame(ocr_set_Frame) start_threshold_detection_Frame.grid(row=1,column=0,pady=15) start_threshold_detection_Button = ttk.Button(start_threshold_detection_Frame,text="阈值检测") start_threshold_detection_Button.grid(row=0,column=0,padx=15) restart_threshold_detection_Button = ttk.Button(start_threshold_detection_Frame,text="重新检测") restart_threshold_detection_Button.grid(row=0,column=1,padx=15) is_Listener_threshold_value_Entry = False transition_frame_num_Label = ttk.Label(ocr_set_Frame, text="符合阈值帧 / 总检测帧 : 0 / 0") transition_frame_num_Label.grid(row=2,column=0) transition_frame_num_Label.grid_forget() now_frame_Dvalue_Label = ttk.Label(ocr_set_Frame, text="当前帧差值: ") now_frame_Dvalue_Label.grid(row=3,column=0) now_frame_Dvalue_Label.grid_forget() log_Frame = ttk.Frame(right_Frame) log_vScrollbar = ttk.Scrollbar(log_Frame) log_vScrollbar.grid(row=0,column=1,sticky='ns') log_Text = tk.Text(log_Frame,width=45,height=10, yscrollcommand=log_vScrollbar.set) log_Text.grid(row=0,column=0,sticky='nsew') log_vScrollbar.config(command=log_Text.yview) #读取配置 config.read(config_file_pathname) if config.get("DEFAULT","ocr") == "PaddleOCR": ocr_choice = 1 try: from paddleocr import PaddleOCR except ModuleNotFoundError: log.error("未能载入库:paddleocr") elif config.get("DEFAULT","ocr") == "EasyOCR": ocr_choice = 2 try: import easyocr except ModuleNotFoundError: log.error("未能载入库:easyocr") #选框 start_x,start_y,end_x,end_y = 0,0,0,0 def draw_box(): global scale,frame_now,start_x,start_y,end_x,end_y,right_x,right_y,left_x,left_y main_rendering_Cap.set(cv2.CAP_PROP_POS_FRAMES,frame_now) frame = main_rendering_Cap.read()[1] frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) if set_filter_Tkbool.get(): frame = img_filter(frame) right_x = min(start_x,end_x) right_y = min(start_y,end_y) left_x = max(start_x,end_x) left_y = max(start_y,end_y) if right_x < 0: right_x = 0 if right_y < 0: right_y = 0 if left_x >= video_review_Label.winfo_width()-4: left_x = video_review_Label.winfo_width()-4 if left_y >= video_review_Label.winfo_height()-4: left_y = video_review_Label.winfo_height()-4 if scale: frame = cv2.resize(frame,(new_frame_width,new_frame_height)) cv2.rectangle(frame,(right_x, right_y, left_x-right_x, left_y-right_y), color=(0,255,255),thickness=1) if scale: left_x_text.set(int(right_x*frame_width/new_frame_width)) left_y_text.set(int(right_y*frame_width/new_frame_width)) right_x_text.set(int(left_x*frame_width/new_frame_width)) right_y_text.set(int(left_y*frame_width/new_frame_width)) else: left_x_text.set(right_x) left_y_text.set(right_y) right_x_text.set(left_x) right_y_text.set(left_y) photo = ImageTk.PhotoImage(Image.fromarray(frame)) video_review_Label.config(image=photo) video_review_Label.image = photo def draw_video_review_MouseDown(event): global start_x, start_y start_x,start_y = event.x, event.y video_review_Label.bind("<Button-1>", draw_video_review_MouseDown) def draw_video_review_MouseDrag(event): global end_x, end_y end_x,end_y = event.x, event.y draw_box() video_review_Label.bind("<B1-Motion>", draw_video_review_MouseDrag) #OCR执行 class SRT: line_num = 0 # half_frame_time:float def __init__(self, path:str): try: if srt_overwrite_Tkbool.get(): f = open(path, 'w') else: f = open(path, 'a') except IOError: log.error("无法打开:"+path) else: f.close() self.path = path self.line_num = 1 # self.half_frame_time = 1/fps def start_write(self): try: self.srt = open(self.path, 'a') except IOError: log.error("无法打开:"+self.path) else: self.is_open = True def writeLine(self, start_time:float, end_time:float, line:str): # start_time -= self.half_frame_time start_time = floor(start_time*1000)/1000 end_time = floor(end_time*1000)/1000 self.srt.write(f"{self.line_num}\n{int(start_time//3600):02d}:{int(start_time%3600//60):02d}:{int(start_time%60):02d},{int(round(start_time%1*1000)):03d} --> {int(end_time//3600):02d}:{int(end_time%3600//60):02d}:{int(end_time%60):02d},{int(round(end_time%1*1000)):03d}\n{line}\n") self.line_num += 1 def end_write(self): self.srt.close() def findThreshold_start(): global end_all_thread,difference_list end_all_thread=False difference_list = [-1]*frame_count # 这里的想的是重新检测时可以防止二次检测,但没考虑到选框改变的情况,所以暂时选择在重新检测时重置list save_config() global ocr_reader,srt if ocr_choice==1: ocr_reader = PaddleOCR(lang=set_language_Entry.get(),use_gpu=open_gpu_Tkbool.get()) elif ocr_choice==2: ocr_reader = easyocr.Reader(set_language_Entry.get().split(','),gpu=open_gpu_Tkbool.get()) srt = SRT(set_srtPath_Entry.get()) input_video_Entry.config(state=tk.DISABLED) input_video_Button.config(state=tk.DISABLED) frame_now_Entry.config(state=tk.DISABLED) draw_box_left_x.config(state=tk.DISABLED) draw_box_left_y.config(state=tk.DISABLED) draw_box_right_x.config(state=tk.DISABLED) draw_box_right_y.config(state=tk.DISABLED) set_srtPath_Entry.config(state=tk.DISABLED) srt_overwrite_set.config(state=tk.DISABLED) set_language_Entry.config(state=tk.DISABLED) open_gpu_set_Checkbutton.config(state=tk.DISABLED) set_filter_set.config(state=tk.DISABLED) retain_color_tolerance_Label.config(state=tk.DISABLED) retain_color1_Entry.config(state=tk.DISABLED) retain_color2_Entry.config(state=tk.DISABLED) start_frame_num_Entry.config(state=tk.DISABLED) set_start_frame_num_Button.config(state=tk.DISABLED) end_frame_num_Entry.config(state=tk.DISABLED) set_end_frame_num_Button.config(state=tk.DISABLED) threshold_value_input_Entry.config(state=tk.DISABLED) start_threshold_detection_Button.config(text="OCR",command=start_OCR) start_threshold_detection_Button.config(state=tk.DISABLED) video_review_Label.unbind("<MouseWheel>") video_review_Label.unbind("<B1-Motion>") video_review_Label.unbind("<Button-1>") video_Progressbar.unbind("<MouseWheel>") video_Progressbar.unbind("<B1-Motion>") video_Progressbar.unbind("<Button-1>") video_frame_Label.unbind("<MouseWheel>") video_frame_Label.unbind("<B1-Motion>") video_frame_Label.unbind("<Button-1>") findThreshold_reading() def findThreshold_end(): global ocr_reader,srt,is_Listener_threshold_value_Entry,frame_now,end_all_thread end_all_thread=True frame_now=end_num#关闭阈值检测和绘制线程 is_Listener_threshold_value_Entry=False#关闭监听 input_video_Entry.config(state=tk.NORMAL) input_video_Button.config(state=tk.NORMAL) frame_now_Entry.config(state=tk.NORMAL) draw_box_left_x.config(state=tk.NORMAL) draw_box_left_y.config(state=tk.NORMAL) draw_box_right_x.config(state=tk.NORMAL) draw_box_right_y.config(state=tk.NORMAL) set_srtPath_Entry.config(state=tk.NORMAL) srt_overwrite_set.config(state=tk.NORMAL) set_language_Entry.config(state=tk.NORMAL) open_gpu_set_Checkbutton.config(state=tk.NORMAL) set_filter_set.config(state=tk.NORMAL) retain_color_tolerance_Label.config(state=tk.NORMAL) retain_color1_Entry.config(state=tk.NORMAL) retain_color2_Entry.config(state=tk.NORMAL) start_frame_num_Entry.config(state=tk.NORMAL) set_start_frame_num_Button.config(state=tk.NORMAL) end_frame_num_Entry.config(state=tk.NORMAL) set_end_frame_num_Button.config(state=tk.NORMAL) restart_threshold_detection_Button.config(state=tk.NORMAL) threshold_value_input_Entry.config(state=tk.NORMAL) transition_frame_num_Label.grid_forget() now_frame_Dvalue_Label.grid_forget() video_review_Label.bind("<MouseWheel>", video_progressbar_mousewheel) video_review_Label.bind("<B1-Motion>", draw_video_review_MouseDrag) video_review_Label.bind("<Button-1>", draw_video_review_MouseDown) video_Progressbar.bind("<MouseWheel>", video_progressbar_mousewheel) video_Progressbar.bind("<B1-Motion>", video_progressbar_leftDrag) video_Progressbar.bind("<Button-1>", video_progressbar_leftDrag) video_frame_Label.bind("<B1-Motion>", video_progressbar_leftDrag) video_frame_Label.bind("<Button-1>", video_progressbar_leftDrag) video_frame_Label.bind("<MouseWheel>", video_progressbar_mousewheel) start_threshold_detection_Button.config(text="阈值检测",command=findThreshold_start,state=tk.NORMAL) if 'srt' in globals(): if hasattr(srt, 'srt'): srt.end_write() del srt if 'ocr_reader' in globals(): del ocr_reader start_threshold_detection_Button.config(command=findThreshold_start) restart_threshold_detection_Button.config(command=findThreshold_end) kernel = np.ones((5,5),np.uint8) def threshold_detection(img1,img2,kernel) -> int: difference = cv2.absdiff(cv2.erode(cv2.erode(cv2.dilate(cv2.Canny(img1,50,240),kernel,iterations=1),kernel,iterations=1),kernel,iterations=1),cv2.erode(cv2.erode(cv2.dilate(cv2.Canny(img2,50,240),kernel,iterations=1),kernel,iterations=1),kernel,iterations=1)) return int(cv2.sumElems(difference)[0]/difference.size*1000) def findThreshold_reading(): # global frame_count,frame_now,start_num,end_num,bedraw_frame global frame_count,frame_now,start_num,end_num video_review_Label.bind("<MouseWheel>", video_progressbar_mousewheel) video_review_Label.bind("<B1-Motion>", draw_video_review_MouseDrag) video_review_Label.bind("<Button-1>", draw_video_review_MouseDown) video_Progressbar.bind("<MouseWheel>", video_progressbar_mousewheel) video_Progressbar.bind("<B1-Motion>", video_progressbar_leftDrag) video_Progressbar.bind("<Button-1>", video_progressbar_leftDrag) video_frame_Label.bind("<B1-Motion>", video_progressbar_leftDrag) video_frame_Label.bind("<Button-1>", video_progressbar_leftDrag) video_frame_Label.bind("<MouseWheel>", video_progressbar_mousewheel) if right_x_text.get()<4 or right_y_text.get()<4: # sec_rendering_Cap.set(cv2.CAP_PROP_POS_FRAMES,0) # _, frame = sec_rendering_Cap.read() right_x_text.set(frame_width) right_y_text.set(frame_height) left_x_text.set(0) left_y_text.set(0) #获取帧范围 start_num,end_num = int(start_frame_num_Entry.get()),int(end_frame_num_Entry.get()) if start_num<0: start_num=0 if end_num>frame_count-1: end_num=frame_count-1 if start_num>end_num: start_num=end_num draw_video_frame_Label_range(start_num, end_num, (27, 241, 255)) flush_video_frame_Label() # if threshold_value_input_Entry.get() != "0":#阈值不为0 生成差值表 sec_rendering_Cap.set(cv2.CAP_PROP_POS_FRAMES,start_num) frame_now = start_num Thread(target=Thread_compute_difference, args=(np.zeros((right_y_text.get()-left_y_text.get(), right_x_text.get()-left_x_text.get(), 3),np.uint8),)).start() Thread(target=Thread_draw_video_progress).start() def Thread_compute_difference(frame_front): global frame_now,is_Listener_threshold_value_Entry while frame_now<=end_num: frame = sec_rendering_Cap.read()[1][left_y_text.get():right_y_text.get(), left_x_text.get():right_x_text.get()] frame_behind = img_filter(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) if difference_list[frame_now]==-1: #写入差值 difference_list[frame_now] = threshold_detection(frame_front, frame_behind, kernel) #下一帧 frame_front = frame_behind frame_now+=1 frame_now=end_num threshold_value_input_Entry.config(state=tk.NORMAL) if not end_all_thread: transition_frame_num_Label.grid() now_frame_Dvalue_Label.grid() is_Listener_threshold_value_Entry = True Thread(target=Listener_threshold_value_Entry).start() start_threshold_detection_Button.config(text="OCR",state=tk.NORMAL) def Thread_draw_video_progress(): # global bedraw_frame,frame_now,end_num global frame_now,end_num,scale,right_x,right_y,left_x,left_y while not end_all_thread: if frame_now>end_num: sleep(0.2) continue if scale: right_x = int(left_x_text.get()*new_frame_width/frame_width) right_y = int(left_y_text.get()*new_frame_width/frame_width) left_x = int(right_x_text.get()*new_frame_width/frame_width) left_y = int(right_y_text.get()*new_frame_width/frame_width) else: right_x = left_x_text.get() right_y = left_y_text.get() left_x = right_x_text.get() left_y = right_y_text.get() jump_to_frame() if frame_now==end_num: break sleep(0.5) def Listener_threshold_value_Entry(): global meet_frame_num total_frame_num = end_num-start_num+1 while is_Listener_threshold_value_Entry: if len(threshold_value_input_Entry.get())>0: if threshold_value_input_Entry.get().isdigit() or threshold_value_input_Entry.get()[0] in ('-','+') and threshold_value_input_Entry.get()[1:].isdigit(): for frame_num in range(0,frame_count): draw_video_frame_Label_frameColor(frame_num, (0,0,0)) meet_frame_num = 0 for frame_num in range(start_num,end_num+1): if difference_list[frame_num] > threshold_value_input_Tkint.get(): meet_frame_num += 1 draw_video_frame_Label_frameColor(frame_num, (237,16,234)) flush_video_frame_Label() transition_frame_num_Label.config(text = f"符合阈值帧 / 总检测帧 : {meet_frame_num} / {total_frame_num}") now_frame_Dvalue_Label.config(text = f"当前帧差值: {difference_list[frame_now]}", foreground=('#ED10EA' if difference_list[frame_now]>threshold_value_input_Tkint.get() else 'black')) sleep(0.5) def start_OCR(): global is_Listener_threshold_value_Entry,frame_now,start_num,end_num,is_Thread_OCR_reading restart_threshold_detection_Button.config(state=tk.DISABLED) threshold_value_input_Entry.config(state=tk.DISABLED) is_Listener_threshold_value_Entry = False frame_now = start_num is_Thread_OCR_reading = True ocr_reading = Thread(target=Thread_OCR_reading) ocr_reading.start() Thread(target=Thread_draw_video_progress).start() def end_OCR(): global is_Thread_OCR_reading,frame_now is_Thread_OCR_reading = False ocr_reading.join() findThreshold_end() start_threshold_detection_Button.config(text="终止",command=lambda:Thread(target=end_OCR).start()) def OCR_API(frame): global ocred_num frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) frame = img_filter(frame) if ocr_choice==1: text=ocr_reader.ocr(frame)[0] if text==None: readed_text=[""] else: readed_text = [line[1][0] for line in text] elif ocr_choice==2: readed_text = ocr_reader.readtext(frame, detail=0) ocred_num+=1 now_frame_Dvalue_Label.config(text = f"OCR进度: {ocred_num} / {meet_frame_num} = {ocred_num/meet_frame_num*100:.2f}%") return '\n'.join(readed_text)+'\n' def Thread_OCR_reading(): global frame_now,ocred_num srt.start_write() ocred_num=0 now_frame_Dvalue_Label.config(foreground=('#ED10EA')) #第一行 previous_line:str previous_time:float for frame_num in range(start_num,end_num+1): if not is_Thread_OCR_reading: srt.end_write() return if difference_list[frame_num] > threshold_value_input_Tkint.get(): frame_now = frame_num sec_rendering_Cap.set(cv2.CAP_PROP_POS_FRAMES,frame_num) previous_line = OCR_API(sec_rendering_Cap.read()[1][left_y_text.get():right_y_text.get(), left_x_text.get():right_x_text.get()]) previous_time = frame_num/fps break current_line = None #中间所有行 for frame_num in range(frame_now+1,end_num+1): if not is_Thread_OCR_reading: srt.end_write() return if difference_list[frame_num] > threshold_value_input_Tkint.get(): frame_now = frame_num sec_rendering_Cap.set(cv2.CAP_PROP_POS_FRAMES,frame_num) current_line = OCR_API(sec_rendering_Cap.read()[1][left_y_text.get():right_y_text.get(), left_x_text.get():right_x_text.get()]) if previous_line != current_line: current_time = frame_num/fps srt.writeLine(previous_time, current_time, previous_line) previous_line, previous_time = current_line, current_time #最后一行 if not current_line: current_line = previous_line srt.writeLine(previous_time, end_num/fps, current_line) srt.end_write() start_threshold_detection_Button.config(text="完成",command=findThreshold_end) root_Tk.mainloop()
42,558
Python
.py
864
41.118056
290
0.681208
op200/Simple_Subtitle_OCR
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)
2,289,799
SS_OCR_CLI.py
op200_Simple_Subtitle_OCR/SS_OCR_CLI.py
import cv2 from PIL import Image, ImageTk import numpy as np from threading import Thread from time import sleep from math import floor import os os.environ['KMP_DUPLICATE_LIB_OK']='True' PROGRAM_NAME = "Simple Subtitle OCR (CLI)" VERSION = "0.6.1" HOME_LINK = "https://github.com/op200/Simple_Subtitle_OCR" from typing import Callable #日志 class log: log_level = 0 @staticmethod def output(info:object): print(info) @staticmethod def exit(): log.error("program interruption") exit() @staticmethod def error(info:object, level:int=110): if level>log.log_level: log.output(f"\033[31m[ERROR]\033[0m {info}") @staticmethod def errore(info:object): log.error(info) log.exit() @staticmethod def warning(info:object, level:int=70): if level>log.log_level: log.output(f"\033[33m[WARNING]\033[0m {info}") @staticmethod def info(info:object, level:int=30): if level>log.log_level: log.output(f"\033[35m[INFO]\033[0m {info}") import sys cmds = sys.argv[1:] input_path:str = None start_frame:int = 0 end_frame:int = None # = the last frame of the video select_box:tuple = (0,0,0,0) srt_path:str = ".\SS_OCR_CLI-output.srt" overwrite_srt:bool = True language:tuple = ("ch",) use_gpu:bool = False threshold:int = 0 ocr_tool_name:str = "paddleocr" fps_force:float = None for cmd in cmds: if cmd=="-v" or cmd=="-version": log.output(f"{PROGRAM_NAME}\nVersion: {VERSION}\n{HOME_LINK}") exit() if cmd=="-h" or cmd=="-help": print(f""" {PROGRAM_NAME} help: -h/-help print help -v/-version print version -i/-input <string> input the path of a video or img sequence default: {input_path} -sf <int in [0:]> set start frame default: {start_frame} -ef <int in [sf:]> set end frame this frame will be input, == [sf:ef+1] in python default: (the last frame of the video) -sb <int:int:int:int> set select box x1:y1:x2:y2 select box is [(x1, x1), (x2-1, y2-1)], == [y2:y1, x2:x1] in python "-sb 0:0:0:0" == "-sb 0:0:(the video's width):(the video's height)" default: 0:0:0:0 -srt <string> set the output srt's path default: ".\SS_OCR_CLI-output.srt" -ow <bool> is it overwrite srt default: {overwrite_srt} -l <string> set language if the OCR tool support plurality of language, separate each word with ',' default: "ch" -gpu <bool> is it use gpu default: {use_gpu} -th <int> set the threshold value if th < 0, threshold detection will be skipped default: {threshold} -ocr <string> set OCR tool's name support: "paddleocr", "easyocr" default: "{ocr_tool_name}" -fps <float> force fps it can change the subtitle's time stamp when it isn't None default: {fps_force} -loglevel <int> log level if it > 20 , some INFO will not be print if it > 40 , all INFO will not be print if it > 60 , some WARRING will not be print if it > 80 , all WARRING will not be print if it > 100, some ERROR will not be print if it > 120, all ERROR will not be print if it > 140, all logs will not be print default: 0 """) exit() for i in range(len(cmds)): # input if cmds[i]=="-i" or cmds[i]=="-input": input_path = cmds[i+1] # startf if cmds[i]=="-sf": try: start_frame = int(cmds[i+1]) except: log.errore("start frame error") # endf if cmds[i]=="-ef": try: end_frame = int(cmds[i+1]) except: log.errore("end frame error") # select box # x1:y1:x2:y2 if cmds[i]=="-sb": try: select_box = tuple(map(int, cmds[i+1].split(':'))) except: log.errore("select box error") if len(select_box)!=4: log.errore("select box error") # srt path if cmds[i]=="-srt": srt_path = cmds[i+1] # overwrite srt if cmds[i]=="-ow": try: overwrite_srt = bool(int(cmds[i+1])) except: log.errore("overwrite srt option error") # language if cmds[i]=="-l": try: language = tuple(cmds[i+1].split(',')) except: log.errore("language setting error") # use GPU if cmds[i]=="-gpu": try: use_gpu = bool(int(cmds[i+1])) except: log.errore("use GPU option error") # threshold if cmds[i]=="-th": try: threshold = int(cmds[i+1]) except: log.errore("threshold value error") # force fps if cmds[i]=="-fps": try: fps_force = float(cmds[i+1]) except: log.errore("force fps value error") # OCR tool # global ocr_tool_name if cmds[i]=="-ocr": ocr_tool_name = cmds[i+1] if not ocr_tool_name in ["paddleocr", "easyocr"]: log.errore("OCR tool name error") # log level if cmds[i]=="-loglevel": try: log.log_level = int(cmds[i+1]) except: log.errore("log level error") log.info("read command complete", 10) log.info("analysis command", 8) if not input_path: log.errore("none file be inputed") # 载入视频 log.info("open video", 8) video_cap = cv2.VideoCapture(input_path) if not video_cap.isOpened(): # log.errore("video can't be readed") pass log.info("open video complete", 10) video_width = int(video_cap.get(cv2.CAP_PROP_FRAME_WIDTH)) video_height = int(video_cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) frame_count = int(video_cap.get(cv2.CAP_PROP_FRAME_COUNT)) fps = fps_force if fps_force else video_cap.get(cv2.CAP_PROP_FPS) log.info(f"video info: {video_width}x{video_height}p {frame_count}F {fps}FPS",35) if end_frame==None: end_frame = frame_count-1 elif end_frame >= frame_count: log.errore("-ef is too large") if end_frame<start_frame: log.errore("the -ef must be >= the -sf") select_frame_num = end_frame - start_frame + 1 if select_box == (0,0,0,0): select_box = (0,0,video_width,video_height) else: select_box = (min(select_box[0],select_box[2]), min(select_box[1],select_box[3]), max(select_box[0],select_box[2]), max(select_box[1],select_box[3]),) log.info("analysis command complete", 10) # 载入OCR库 log.info("import ocr", 8) if ocr_tool_name == "paddleocr": try: from paddleocr import PaddleOCR except ModuleNotFoundError: log.errore("from paddleocr import PaddleOCR - failed") ocr_choice=1 ocr_reader = PaddleOCR(show_log=False, lang=language[0], use_gpu=use_gpu) elif ocr_tool_name == "easyocr": try: import easyocr except ModuleNotFoundError: log.errore("import easyocr - failed") ocr_choice=2 ocr_reader = easyocr.Reader(language, gpu=use_gpu) log.info("import ocr complete", 10) # 阈值检测 difference_list = [False]*select_frame_num # 初始化差值表 kernel = np.ones((5,5),np.uint8) def threshold_detection(img1,img2,kernel) -> int: difference = cv2.absdiff( cv2.erode( cv2.erode( cv2.dilate(cv2.Canny(img1,50,240),kernel,iterations=1), kernel,iterations=1 ), kernel,iterations=1 ), cv2.erode( cv2.erode( cv2.dilate(cv2.Canny(img2,50,240),kernel,iterations=1), kernel,iterations=1 ), kernel,iterations=1 ) ) return int(cv2.sumElems(difference)[0]/difference.size*1000) if threshold>=0: log.info("difference calculation", 8) frame_front = np.zeros((select_box[3]-select_box[1], select_box[2]-select_box[0], 3),np.uint8) video_cap.set(cv2.CAP_PROP_POS_FRAMES,start_frame) for frame_num in range(start_frame,end_frame+1): frame_behind = video_cap.read()[1][select_box[1]:select_box[3], select_box[0]:select_box[2]] difference_list[frame_num-start_frame] = (threshold_detection(frame_front, frame_behind, kernel) > threshold) frame_front = frame_behind threshold_pass_list = [i for i,v in enumerate(difference_list) if v] log.info("difference calculation complete", 10) else: threshold_pass_list = list(range(start_frame,end_frame+1)) threshold_pass_num = len(threshold_pass_list) log.info(f"passed / selected / total: {threshold_pass_num} / {select_frame_num} / {frame_count}") # print all frames char preview all_frames_preview = ( '.'*start_frame + ''.join(['|' if t else '*' for t in difference_list]) + '.'*(frame_count-end_frame-1) ) interval = max(round(fps),5) log.info((lambda: "frames preview:\n" + '\n'.join([ f"{i:>{len(str(frame_count))}} F\n" + all_frames_preview[i:i+interval] for i in range(0, len(all_frames_preview), interval) ]))()) # OCR, 启动! class SRT: line_num = 0 def __init__(self, path:str): try: if overwrite_srt: f = open(path, 'w') else: f = open(path, 'a') except IOError: log.error("can not open srt:"+path) log.info(f"difference_list:{difference_list}") log.exit() else: f.close() self.path = path self.line_num = 1 def start_write(self): try: self.srt = open(self.path, 'a') except IOError: log.error("can not open srt:"+self.path) log.info(f"difference_list:{difference_list}") log.exit() def writeLine(self, start_time:float, end_time:float, line:str): start_time = floor(start_time*1000)/1000 end_time = floor(end_time*1000)/1000 self.srt.write(f"{self.line_num}\n{int(start_time//3600):02d}:{int(start_time%3600//60):02d}:{int(start_time%60):02d},{int(round(start_time%1*1000)):03d} --> {int(end_time//3600):02d}:{int(end_time%3600//60):02d}:{int(end_time%60):02d},{int(round(end_time%1*1000)):03d}\n{line}\n") self.line_num += 1 def end_write(self): self.srt.close() ocred_num:int = 0 def OCR_API(frame): global ocred_num,select_frame_num if ocr_choice==1: text=ocr_reader.ocr(frame)[0] if text==None: readed_text=[""] else: readed_text = [line[1][0] for line in text] elif ocr_choice==2: readed_text = ocr_reader.readtext(frame, detail=0) ocred_num+=1 _ = f"OCR进度: {ocred_num} / {select_frame_num} = {ocred_num/select_frame_num*100:.2f}%" return '\n'.join(readed_text)+'\n' log.info("OCR start", 10) srt = SRT(srt_path) srt.start_write() if threshold>=0: # 第一行 previous_time = threshold_pass_list[0]/fps video_cap.set(cv2.CAP_PROP_POS_FRAMES, threshold_pass_list[0]) previous_line = OCR_API(video_cap.read()[1][select_box[1]:select_box[3], select_box[0]:select_box[2]]) # 中间行 for frame_num in threshold_pass_list[1:]: video_cap.set(cv2.CAP_PROP_POS_FRAMES,frame_num) current_line = OCR_API(video_cap.read()[1][select_box[1]:select_box[3], select_box[0]:select_box[2]]) if previous_line != current_line: current_time = frame_num/fps srt.writeLine(previous_time, current_time, previous_line) previous_line, previous_time = current_line, current_time #最后一行 srt.writeLine(previous_time, threshold_pass_list[-1]/fps, previous_line) srt.end_write() else: # 第一行 previous_time = start_frame/fps video_cap.set(cv2.CAP_PROP_POS_FRAMES, start_frame) previous_line = OCR_API(video_cap.read()[1][select_box[1]:select_box[3], select_box[0]:select_box[2]]) previous_time = frame_num/fps # 中间行 for frame_num in threshold_pass_list[1:]: current_line = OCR_API(video_cap.read()[1][select_box[1]:select_box[3], select_box[0]:select_box[2]]) if previous_line != current_line: current_time = frame_num/fps srt.writeLine(previous_time, current_time, previous_line) previous_line, previous_time = current_line, current_time #最后一行 srt.writeLine(previous_time, threshold_pass_list[-1]/fps, previous_line) srt.end_write() log.info("OCR complete", 12)
12,873
Python
.py
360
27.797222
290
0.598738
op200/Simple_Subtitle_OCR
8
2
0
GPL-3.0
9/5/2024, 10:48:43 PM (Europe/Amsterdam)